From eb8f806023f5a0f49cd48d8efda5563077a97d31 Mon Sep 17 00:00:00 2001 From: Robert B Gordon Date: Fri, 5 Sep 2014 15:05:01 -0500 Subject: [PATCH] add gorm field tag "update" This attempts to address a concern in issues #202 and #192. It adds a gorm field tag that allows one to specify that the tagged field should always be updated. (essentially it forces isBlank to always be false) --- scope.go | 7 +++++-- update_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/scope.go b/scope.go index 9db9f259..3fd49c73 100644 --- a/scope.go +++ b/scope.go @@ -287,7 +287,6 @@ func (scope *Scope) fieldFromStruct(fieldStruct reflect.StructField, withRelatio value := scope.IndirectValue().FieldByName(fieldStruct.Name) indirectValue := reflect.Indirect(value) field.Field = value - field.IsBlank = isBlank(value) // Search for primary key tag identifier settings := parseTagSetting(fieldStruct.Tag.Get("gorm")) @@ -304,7 +303,11 @@ func (scope *Scope) fieldFromStruct(fieldStruct reflect.StructField, withRelatio if fieldStruct.Tag.Get(tagIdentifier) == "-" { field.IsIgnored = true } - + if _, ok := settings["UPDATE"]; ok { + field.IsBlank = false + } else { + field.IsBlank = isBlank(value) + } if !field.IsIgnored { // parse association if !indirectValue.IsValid() { diff --git a/update_test.go b/update_test.go index 7302bb8a..c142a3d2 100644 --- a/update_test.go +++ b/update_test.go @@ -158,3 +158,41 @@ func TestUpdateColumn(t *testing.T) { t.Errorf("updatedAt should not be updated with update column") } } + +type Always struct { + Id int64 + Name string + Code string + Price int64 `gorm:"update"` +} + +func TestAlwaysUpdate(t *testing.T) { + DB.DropTable(&Always{}) + DB.CreateTable(&Always{}) + + obj1 := Always{Name: "obj1", Code: "code_1", Price: 10} + obj2 := Always{Name: "obj2", Code: "code_2", Price: 20} + + // save initial + DB.Save(&obj1).Save(&obj2).UpdateColumn(map[string]interface{}{"code": "columnUpdate2"}) + // fetch and verify + var obj3, obj4 Always + DB.First(&obj3, obj1.Id) + if obj3.Code != "code_1" || obj3.Price != 10 { + t.Errorf("obj1 was not saved correctly: expected: %#v got: %#v", obj1, obj3) + } + DB.First(&obj4, obj2.Id) + if obj4.Code != "columnUpdate2" || obj4.Price != 20 { + t.Errorf("obj2 was not saved correctly: expected: %#v got: %#v", obj2, obj4) + } + + // now update via struct price should change to zero + obj5 := Always{Name: "obj2update", Code: "code_2"} + DB.Model(obj5).Updates(obj5) + + var obj6 Always + DB.First(&obj6, obj2.Id) + if obj6.Code != "code_2" || obj6.Name != "obj2update" || obj6.Price != 0 { + t.Errorf("obj2 was not saved correctly: got: %#v", obj6) + } +}