app/attribute/attribute.go

75 lines
1.5 KiB
Go
Raw Normal View History

2021-12-18 17:37:44 +00:00
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
2021-12-18 18:12:41 +00:00
func Init() {
2021-12-18 17:37:44 +00:00
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 {
2021-12-18 18:12:41 +00:00
panic(err)
2021-12-18 17:37:44 +00:00
}
}
2021-12-18 17:54:17 +00:00
func Add(Key, Description, Default string) error {
2021-12-18 18:01:56 +00:00
result := store.DB.Exec(`select "value" from "attributes" where "key" = ?`, Key)
if result.RowsAffected != 0 {
return nil
}
2021-12-18 17:37:44 +00:00
a := &Attribute{
Key: Key,
Description: Description,
Default: Default,
2021-12-18 17:54:17 +00:00
Value: Default,
2021-12-18 17:37:44 +00:00
}
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
}