From a84c90f4597a2b0670f7d9bddfdc9e3856bc4da3 Mon Sep 17 00:00:00 2001 From: Evan Chen Date: Sun, 19 Dec 2021 02:44:34 +0800 Subject: [PATCH] update --- attribute/attribute.go | 12 ++++++++---- attribute/attribute_test.go | 22 ++++++++++++++++++++++ attribute/errors.go | 6 ++++++ 3 files changed, 36 insertions(+), 4 deletions(-) create mode 100644 attribute/attribute_test.go diff --git a/attribute/attribute.go b/attribute/attribute.go index bace623..ea28fbd 100644 --- a/attribute/attribute.go +++ b/attribute/attribute.go @@ -33,9 +33,11 @@ func Init() { } func Add(Key, Description, Default string) error { - result := store.DB.Exec(`select "value" from "attributes" where "key" = ?`, Key) - if result.RowsAffected != 0 { - return nil + ctr := 0 + store.DB.Raw(`select count(*) from "attributes" where "key" = ?`, Key). + Scan(&ctr) + if ctr != 0 { + return ErrorAttributeExist } a := &Attribute{ Key: Key, @@ -43,7 +45,9 @@ func Add(Key, Description, Default string) error { Default: Default, Value: Default, } - return store.DB.Create(a).Error + err := store.DB.Create(a).Error + + return err } func RestoreDefault(key string) error { diff --git a/attribute/attribute_test.go b/attribute/attribute_test.go new file mode 100644 index 0000000..40a5af1 --- /dev/null +++ b/attribute/attribute_test.go @@ -0,0 +1,22 @@ +package attribute + +import ( + "fmt" + "testing" + + "github.com/spf13/viper" + "kumoly.io/kumoly/app/store" +) + +func TestAttr(t *testing.T) { + viper.Set("data", "work") + viper.Set("db.type", "sqlite") + store.Setup() + Init() + fmt.Println(Add("test", "", "1")) + fmt.Println(Add("test1", "", "2")) + fmt.Println(Add("test2", "", "2")) + fmt.Println(Add("test3", "", "2")) + fmt.Println(Set("test", "reset")) + fmt.Println(Get("test")) +} diff --git a/attribute/errors.go b/attribute/errors.go index 78342ba..90286c5 100644 --- a/attribute/errors.go +++ b/attribute/errors.go @@ -6,6 +6,12 @@ import ( "kumoly.io/kumoly/app/errors" ) +var ErrorAttributeExist = errors.Error{ + Code: http.StatusBadRequest, + ID: "ErrorAttributeExist", + Message: "Attribute already exist", +} + var ErrorAttributeNotFound = errors.Error{ Code: http.StatusNotFound, ID: "ErrorTokenNotValid",