2022-09-10 11:39:07 +00:00
|
|
|
package counter
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/pkg/errors"
|
2022-10-22 22:08:02 +00:00
|
|
|
"gorm.io/gorm"
|
|
|
|
"gorm.io/gorm/clause"
|
|
|
|
|
2022-11-02 21:38:14 +00:00
|
|
|
"github.com/Luzifer/twitch-bot/v3/pkg/database"
|
2022-09-10 11:39:07 +00:00
|
|
|
)
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
type (
|
2023-10-23 18:28:58 +00:00
|
|
|
Counter struct {
|
2022-10-22 22:08:02 +00:00
|
|
|
Name string `gorm:"primaryKey"`
|
|
|
|
Value int64
|
|
|
|
}
|
|
|
|
)
|
2022-09-10 11:39:07 +00:00
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
func GetCounterValue(db database.Connector, counterName string) (int64, error) {
|
2023-10-23 18:28:58 +00:00
|
|
|
var c Counter
|
2022-09-10 11:39:07 +00:00
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
err := db.DB().First(&c, "name = ?", counterName).Error
|
2022-09-10 11:39:07 +00:00
|
|
|
switch {
|
|
|
|
case err == nil:
|
2022-10-22 22:08:02 +00:00
|
|
|
return c.Value, nil
|
2022-09-10 11:39:07 +00:00
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
case errors.Is(err, gorm.ErrRecordNotFound):
|
2022-09-10 11:39:07 +00:00
|
|
|
return 0, nil
|
|
|
|
|
|
|
|
default:
|
|
|
|
return 0, errors.Wrap(err, "querying counter")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
func UpdateCounter(db database.Connector, counterName string, value int64, absolute bool) error {
|
2022-09-10 11:39:07 +00:00
|
|
|
if !absolute {
|
2022-10-22 22:08:02 +00:00
|
|
|
cv, err := GetCounterValue(db, counterName)
|
2022-09-10 11:39:07 +00:00
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "getting previous value")
|
|
|
|
}
|
|
|
|
|
|
|
|
value += cv
|
|
|
|
}
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
return errors.Wrap(
|
|
|
|
db.DB().Clauses(clause.OnConflict{
|
|
|
|
Columns: []clause.Column{{Name: "name"}},
|
|
|
|
DoUpdates: clause.AssignmentColumns([]string{"value"}),
|
2023-10-23 18:28:58 +00:00
|
|
|
}).Create(Counter{Name: counterName, Value: value}).Error,
|
2022-10-22 22:08:02 +00:00
|
|
|
"storing counter value",
|
2022-09-10 11:39:07 +00:00
|
|
|
)
|
|
|
|
}
|
2023-10-23 18:28:58 +00:00
|
|
|
|
|
|
|
func getCounterRank(db database.Connector, prefix, name string) (rank, count int64, err error) {
|
|
|
|
var cc []Counter
|
|
|
|
|
|
|
|
err = db.DB().
|
|
|
|
Order("value DESC").
|
|
|
|
Find(&cc, "name LIKE ?", prefix+"%").
|
|
|
|
Error
|
|
|
|
if err != nil {
|
|
|
|
return 0, 0, errors.Wrap(err, "querying counters")
|
|
|
|
}
|
|
|
|
|
|
|
|
for i, c := range cc {
|
|
|
|
count++
|
|
|
|
if c.Name == name {
|
|
|
|
rank = int64(i + 1)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return rank, count, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func getCounterTopList(db database.Connector, prefix string, n int) ([]Counter, error) {
|
|
|
|
var cc []Counter
|
|
|
|
|
|
|
|
err := db.DB().
|
|
|
|
Order("value DESC").
|
|
|
|
Limit(n).
|
|
|
|
Find(&cc, "name LIKE ?", prefix+"%").
|
|
|
|
Error
|
|
|
|
|
|
|
|
return cc, errors.Wrap(err, "querying counters")
|
|
|
|
}
|