app/attribute/attribute.go

72 lines
1.4 KiB
Go

package attribute
import (
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"kumoly.io/kumoly/app/store"
)
type Attribute struct {
ID uint `gorm:"primaryKey"`
CreatedAt time.Time
UpdatedAt time.Time
Key string `gorm:"unique;not null"`
Description string
Default string
Value string
}
var l zerolog.Logger
func Init() error {
l = log.With().Str("mod", "attribute").Logger()
l.Debug().Str("service", "attribute.Service").
Msg("Migrating database for attribute.Service ...")
err := store.Migrate(&Attribute{})
if err != nil {
return err
}
return nil
}
func Add(Key, Description, Default, Value string) error {
a := &Attribute{
Key: Key,
Description: Description,
Default: Default,
Value: Value,
}
return store.DB.Create(a).Error
}
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
}