forked from kamaln7/karmabot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.go
216 lines (172 loc) · 4.38 KB
/
database.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
package database
import (
"database/sql"
"errors"
"strings"
"time"
"github.com/aybabtme/log"
// import the sqlite3 driver
_ "github.com/mattn/go-sqlite3"
)
// Config contains the necessary config options to
// connect to an sqlite3 database.
type Config struct {
Path string
Log *log.Log
}
// A DB in an instance of a karmabot database.
type DB struct {
Config *Config
SQL *sql.DB
}
// Points is a karma record containing info about
// a karma operation.
type Points struct {
From, To, Reason string
Points int
}
// Throwback is a karma operation that has happened
type Throwback struct {
Points
Timestamp time.Time
}
// The Leaderboard lists the top X users.
type Leaderboard []*User
// A User is an entry in the Leaderboard.
type User struct {
Name string
Points int
}
// ErrNoSuchUser is returned when a user lookup
// is performed on a non-existent user
var ErrNoSuchUser = errors.New("no such user")
// New returns a new instance of a karmabot database
// and initializes it
func New(config *Config) (*DB, error) {
instance := &DB{
Config: config,
}
err := instance.Init()
if err != nil {
return nil, err
}
return instance, nil
}
// Init initializes an sqlite3 database in order
// for karmabot to be able to use it
func (db *DB) Init() error {
sqlite, err := sql.Open("sqlite3", db.Config.Path)
if err != nil {
return err
}
db.SQL = sqlite
return db.createTable()
}
func (db *DB) createTable() error {
schema := strings.Replace(
`create table if not exists karma (
^id^ integer primary key,
^from^ text not null,
^to^ text not null,
^points^ integer not null,
^reason^ text,
^timestamp^ text not null default (datetime('now'))
)`,
"^", "`", -1)
_, err := db.SQL.Exec(schema)
if err != nil {
return err
}
_, err = db.SQL.Exec("create index if not exists idx_to on karma(`to`);")
if err != nil {
return err
}
return nil
}
// InsertPoints inserts a Points object into the database.
func (db *DB) InsertPoints(points *Points) error {
stmt, err := db.SQL.Prepare("insert into karma (`from`, `to`, `reason`, `points`) values(?, ?, ?, ?)")
if err != nil {
return err
}
defer stmt.Close()
_, err = stmt.Exec(points.From, points.To, points.Reason, points.Points)
return err
}
// GetUser returns info about a user.
func (db *DB) GetUser(name string) (*User, error) {
stmt, err := db.SQL.Prepare("select count(`to`) as `count` from karma where `to` = ?")
if err != nil {
return nil, err
}
defer stmt.Close()
user := &User{
Name: name,
}
var userExists int
err = stmt.QueryRow(user.Name).Scan(&userExists)
if err != nil {
return nil, err
}
if userExists == 0 {
return nil, ErrNoSuchUser
}
stmt, err = db.SQL.Prepare("select sum(`points`) as `points` from karma where `to` = ?")
if err != nil {
return nil, err
}
defer stmt.Close()
err = stmt.QueryRow(user.Name).Scan(&user.Points)
if err != nil {
return nil, err
}
return user, nil
}
// GetLeaderboard returns the leaderboard with the top X users.
func (db *DB) GetLeaderboard(limit int) (Leaderboard, error) {
rows, err := db.SQL.Query("select `to`, sum(`points`) as `points` from karma group by `to` order by `points` desc limit ?", limit)
if err != nil {
return nil, err
}
defer rows.Close()
var leaderboard Leaderboard
for rows.Next() {
user := &User{}
err := rows.Scan(&user.Name, &user.Points)
if err != nil {
return nil, err
}
leaderboard = append(leaderboard, user)
}
return leaderboard, nil
}
// GetTotalPoints returns the amount of points given or taken
// for all users.
func (db *DB) GetTotalPoints() (int, error) {
var res int
err := db.SQL.QueryRow("select sum(abs(`points`)) from karma").Scan(&res)
if err != nil {
return 0, err
}
return res, nil
}
// GetThrowback returns a random karma operation on a specific user
func (db *DB) GetThrowback(user string) (*Throwback, error) {
var (
record = &Throwback{}
timestamp = ""
)
err := db.SQL.QueryRow("select `from`, `to`, `reason`, `points`, `timestamp` from karma where `to` = ? and `id` >= (abs(random()) % (select max(`id`) from karma)) limit 1", user).Scan(&record.From, &record.To, &record.Reason, &record.Points.Points, ×tamp)
switch err {
case nil:
case sql.ErrNoRows:
return nil, ErrNoSuchUser
default:
return nil, err
}
record.Timestamp, err = time.Parse("2006-01-02 15:04:05", timestamp)
if err != nil {
return nil, err
}
return record, nil
}