-
Notifications
You must be signed in to change notification settings - Fork 915
/
sql.go
70 lines (56 loc) · 1.44 KB
/
sql.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
package configstore
import (
"github.com/jinzhu/gorm"
"github.com/jonas747/yagpdb/common"
"github.com/sirupsen/logrus"
"golang.org/x/net/context"
"math/rand"
"strings"
"time"
)
const MaxRetries = 1000
type Postgres struct{}
// conf is requried to be a pointer value
func (p *Postgres) GetGuildConfig(ctx context.Context, guildID int64, conf GuildConfig) error {
currentRetries := 0
for {
err := common.GORM.Where("guild_id = ?", guildID).First(conf).Error
if err == nil {
if currentRetries > 1 {
logrus.Info("Suceeded after ", currentRetries, " retries")
}
return nil
}
if err == gorm.ErrRecordNotFound {
return ErrNotFound
}
if strings.Contains(err.Error(), "sorry, too many clients already") {
time.Sleep(time.Millisecond * 10 * time.Duration(rand.Intn(10)))
currentRetries++
if currentRetries > MaxRetries {
return err
}
continue
}
return err
}
return nil
}
// conf is requried to be a pointer value
func (p *Postgres) SetGuildConfig(ctx context.Context, conf GuildConfig) error {
err := common.GORM.Save(conf).Error
if err != nil {
return err
}
InvalidateGuildCache(conf, conf)
return nil
}
func (p *Postgres) SetIfLatest(ctx context.Context, conf GuildConfig) (updated bool, err error) {
result := common.GORM.Where("updated_at = ?", conf.GetUpdatedAt()).Save(conf)
updated = result.RowsAffected > 0
err = result.Error
if err == nil {
InvalidateGuildCache(conf, conf)
}
return
}