app/attribute/attribute.go

80 lines
1.6 KiB
Go

package attribute
import (
"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"`
Description string
Value string
Default string
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, Description, Default string) error {
ctr := 0
store.DB.Raw(`select count(*) from "attributes" where "key" = ?`, Key).
Scan(&ctr)
if ctr != 0 {
return ErrorAttributeExist
}
a := &Attribute{
Key: Key,
Description: Description,
Default: Default,
Value: Default,
}
err := store.DB.Create(a).Error
return err
}
func RestoreDefault(key string) error {
result := store.DB.Exec(`update "attributes" set value = (
select "default" from "attributes" where "key" = ?
) where "key" = ?`, key, key)
if result.RowsAffected == 0 {
return ErrorAttributeNotFound
}
return result.Error
}
func Get(key string) string {
var value string
store.DB.
Raw(`select "value" from "attributes" where "key" = ?`, key).
Scan(&value)
return 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
}