forked from knadh/niltalk
/
db.go
124 lines (95 loc) · 2.27 KB
/
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
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
// Niltalk, April 2015
// https://niltalk.com
// https://github.com/goniltalk/niltalk
// License AGPL3
package main
import (
"errors"
"time"
"github.com/garyburd/redigo/redis"
)
type DBpool struct {
pool redis.Pool
}
type DBconn struct {
conn redis.Conn
}
// Initialize a db pool.
func NewDBpool(address string, password string, active int, idle int) *DBpool {
pool := redis.Pool{
MaxActive: active,
MaxIdle: idle,
Dial: func() (redis.Conn, error) {
c, err := redis.DialTimeout("tcp", address, time.Duration(5)*time.Second, time.Duration(5)*time.Second, time.Duration(5)*time.Second)
if err != nil {
return nil, err
}
if password != "" {
c.Do("AUTH", password)
}
return c, err
},
}
return &DBpool{pool: pool}
}
// Get a connection from the pool.
func (dp *DBpool) Get() *DBconn {
return &DBconn{conn: dp.pool.Get()}
}
// Close the pool.
func (dp *DBpool) Close() {
dp.pool.Close()
}
// Retrieve a map from the db.
func (db *DBconn) GetMap(key string, out interface{}) (bool, error) {
res, err := redis.Values(db.conn.Do("HGETALL", key))
if err != nil {
return false, errors.New("Failed to load from DB")
}
// No such entry.
if len(res) == 0 {
return false, nil
}
redis.ScanStruct(res, out)
return true, nil
}
// Write a map to the db.
func (db *DBconn) PutMap(args ...interface{}) error {
_, err := db.conn.Do("HMSET", args...)
return err
}
// Write a set to the db.
func (db *DBconn) PutSet(args ...interface{}) error {
_, err := db.conn.Do("SADD", args...)
return err
}
// Set a key's expiry.
func (db *DBconn) Expire(key string, seconds int) error {
_, err := db.conn.Do("EXPIRE", key, seconds)
return err
}
// Delete a key.
func (db *DBconn) Delete(key string) error {
_, err := db.conn.Do("DEL", key)
return err
}
// Check if a key exists in the db.
func (db *DBconn) Exists(key string) (bool, error) {
exists, err := redis.Bool(db.conn.Do("EXISTS", key))
if err != nil {
return false, err
}
return exists, nil
}
// Check if a value exists in a set.
func (db *DBconn) SetValueExists(key string, value string) (bool, error) {
exists, err := redis.Bool(db.conn.Do("SISMEMBER", key, value))
if err != nil {
return false, err
}
return exists, nil
}
// Close a connection.
func (db *DBconn) Close() {
db.conn.Close()
}