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)
This commit is contained in:
Robert B Gordon 2014-09-05 15:05:01 -05:00
parent b12c6d78a3
commit eb8f806023
2 changed files with 43 additions and 2 deletions

View File

@ -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() {

View File

@ -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)
}
}