forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
local_incr_ids.go
62 lines (51 loc) · 1.56 KB
/
local_incr_ids.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 common
import (
"database/sql"
"strconv"
"emperror.dev/errors"
"github.com/mediocregopher/radix/v3"
)
// GenLocalIncrID creates a new or incremements a existing local id incrememter
// used to have per guild id's
//
// GenLocalIncrID is deprecated and GenLocalIncrIDPQ should be used instead
func GenLocalIncrID(guildID int64, key string) (int64, error) {
var id int64
err := RedisPool.Do(radix.Cmd(&id, "HINCRBY", "local_ids:"+strconv.FormatInt(guildID, 10), key, "1"))
if err != nil {
logger.WithError(err).WithField("guild", guildID).WithField("key", key).Error("failed incrementing local id")
}
return id, err
}
const localIDsSchema = `
CREATE TABLE IF NOT EXISTS local_incr_ids (
guild_id BIGINT NOT NULL,
key TEXT NOT NULL,
last BIGINT NOT NULL,
last_updated TIMESTAMP WITH TIME ZONE NOT NULL,
PRIMARY KEY(guild_id, key)
)
`
// GenLocalIncrIDPQ creates a new or incremements a existing local id incrememter
// used to have per guild id's
//
// GenLocalIncrIDPQ differs from GenLocalIncrID in that it uses postgres instead of redis
func GenLocalIncrIDPQ(tx *sql.Tx, guildID int64, key string) (int64, error) {
const query = `INSERT INTO local_incr_ids (guild_id, key, last, last_updated)
VALUES ($1, $2, 1, now())
ON CONFLICT (guild_id, key)
DO UPDATE SET last = local_incr_ids.last + 1
RETURNING last;`
var row *sql.Row
if tx == nil {
row = PQ.QueryRow(query, guildID, key)
} else {
row = tx.QueryRow(query, guildID, key)
}
var newID int64
err := row.Scan(&newID)
if err != nil {
return 0, errors.WithStackIf(err)
}
return newID, nil
}