app/attribute/attribute.go

101 lines
1.8 KiB
Go

package attribute
import (
"sync"
"time"
"github.com/rs/zerolog"
"kumoly.io/kumoly/app/store"
"kumoly.io/kumoly/app/util"
)
type Attribute struct {
ID uint `gorm:"primaryKey"`
Key string `gorm:"unique;not null"`
Name string
Description string
Value string
Default string
NeedRestart bool
CreatedAt time.Time
UpdatedAt time.Time
}
var l zerolog.Logger
func Init() {
l = util.Klog.With().Str("mod", "attribute").Logger()
l.Debug().Str("service", "attribute.Service").
Msg("Migrating database for attribute.Service ...")
err := store.Migrate(&Attribute{})
if err != nil {
panic(err)
}
}
func Add(Key, Name, Description, Default string, NeedRestart bool) error {
ctr := 0
store.DB.Raw(`select count(*) from "attributes" where "key" = ?`, Key).
Scan(&ctr)
if ctr != 0 {
return ErrorAttributeExist
}
a := &Attribute{
Key: Key,
Name: Name,
Description: Description,
Default: Default,
Value: Default,
NeedRestart: NeedRestart,
}
err := store.DB.Create(a).Error
return err
}
func RestoreDefault(key string) error {
result := store.DB.Exec(`update "attributes" set value = "default" where "key" = ?`, key)
if result.RowsAffected == 0 {
return ErrorAttributeNotFound
}
return result.Error
}
func Get(key string) string {
a := &Attribute{}
store.DB.Select("value", "default").First(a, "key = ?", key)
if a.Value == "" {
return a.Default
}
return a.Value
}
func Set(key, value string) error {
result := store.DB.Exec(`update "attributes" set value = ? where "key" = ?`,
value, key)
if result.RowsAffected == 0 {
return ErrorAttributeNotFound
}
return result.Error
}
var load []func()
var loadLock sync.Mutex
func AddSoftLoad(f func()) {
loadLock.Lock()
load = append(load, f)
loadLock.Unlock()
}
func Load() {
for _, f := range load {
if f != nil {
f()
}
}
}