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 (
|
|
|
|
counter struct {
|
|
|
|
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) {
|
|
|
|
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"}),
|
|
|
|
}).Create(counter{Name: counterName, Value: value}).Error,
|
|
|
|
"storing counter value",
|
2022-09-10 11:39:07 +00:00
|
|
|
)
|
|
|
|
}
|