2022-09-10 11:39:07 +00:00
|
|
|
package variables
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/pkg/errors"
|
2022-10-22 22:08:02 +00:00
|
|
|
"gorm.io/gorm"
|
|
|
|
"gorm.io/gorm/clause"
|
2022-09-10 11:39:07 +00:00
|
|
|
|
2022-10-23 13:06:45 +00:00
|
|
|
"github.com/Luzifer/twitch-bot/v2/pkg/database"
|
2022-10-22 22:08:02 +00:00
|
|
|
)
|
2022-09-10 11:39:07 +00:00
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
type (
|
|
|
|
variable struct {
|
|
|
|
Name string `gorm:"primaryKey"`
|
|
|
|
Value string
|
|
|
|
}
|
|
|
|
)
|
2022-09-10 11:39:07 +00:00
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
func GetVariable(db database.Connector, key string) (string, error) {
|
|
|
|
var v variable
|
|
|
|
err := db.DB().First(&v, "name = ?", key).Error
|
2022-09-10 11:39:07 +00:00
|
|
|
switch {
|
|
|
|
case err == nil:
|
2022-10-22 22:08:02 +00:00
|
|
|
return v.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 "", nil // Compatibility to old behavior
|
|
|
|
|
|
|
|
default:
|
|
|
|
return "", errors.Wrap(err, "getting value from database")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
func SetVariable(db database.Connector, key, value string) error {
|
|
|
|
return errors.Wrap(
|
|
|
|
db.DB().Clauses(clause.OnConflict{
|
|
|
|
Columns: []clause.Column{{Name: "name"}},
|
|
|
|
DoUpdates: clause.AssignmentColumns([]string{"value"}),
|
|
|
|
}).Create(variable{Name: key, Value: value}).Error,
|
|
|
|
"updating value in database",
|
2022-09-10 11:39:07 +00:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2022-10-22 22:08:02 +00:00
|
|
|
func RemoveVariable(db database.Connector, key string) error {
|
|
|
|
return errors.Wrap(
|
|
|
|
db.DB().Delete(&variable{}, "name = ?", key).Error,
|
|
|
|
"deleting value in database",
|
2022-09-10 11:39:07 +00:00
|
|
|
)
|
|
|
|
}
|