fix: stmt.Changed zero value filed behavior (#5281)

* fix: stmt.Changed zero value filed behavior

* chore: rename var
This commit is contained in:
Cr 2022-04-24 09:08:52 +08:00 committed by GitHub
parent 395606ac7c
commit 9b80fe9e96
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 5 deletions

View File

@ -609,10 +609,10 @@ func (stmt *Statement) Changed(fields ...string) bool {
changed := func(field *schema.Field) bool { changed := func(field *schema.Field) bool {
fieldValue, _ := field.ValueOf(stmt.Context, modelValue) fieldValue, _ := field.ValueOf(stmt.Context, modelValue)
if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && !restricted) { if v, ok := selectColumns[field.DBName]; (ok && v) || (!ok && !restricted) {
if v, ok := stmt.Dest.(map[string]interface{}); ok { if mv, mok := stmt.Dest.(map[string]interface{}); mok {
if fv, ok := v[field.Name]; ok { if fv, ok := mv[field.Name]; ok {
return !utils.AssertEqual(fv, fieldValue) return !utils.AssertEqual(fv, fieldValue)
} else if fv, ok := v[field.DBName]; ok { } else if fv, ok := mv[field.DBName]; ok {
return !utils.AssertEqual(fv, fieldValue) return !utils.AssertEqual(fv, fieldValue)
} }
} else { } else {
@ -622,6 +622,9 @@ func (stmt *Statement) Changed(fields ...string) bool {
} }
changedValue, zero := field.ValueOf(stmt.Context, destValue) changedValue, zero := field.ValueOf(stmt.Context, destValue)
if v {
return !utils.AssertEqual(changedValue, fieldValue)
}
return !zero && !utils.AssertEqual(changedValue, fieldValue) return !zero && !utils.AssertEqual(changedValue, fieldValue)
} }
} }

View File

@ -375,13 +375,19 @@ func TestSetColumn(t *testing.T) {
t.Errorf("invalid data after update, got %+v", product) t.Errorf("invalid data after update, got %+v", product)
} }
// Code changed, price should changed
DB.Model(&product).Select("Name", "Code", "Price").Updates(Product3{Name: "Product New4", Code: ""})
if product.Name != "Product New4" || product.Price != 320 || product.Code != "" {
t.Errorf("invalid data after update, got %+v", product)
}
DB.Model(&product).UpdateColumns(Product3{Code: "L1215"}) DB.Model(&product).UpdateColumns(Product3{Code: "L1215"})
if product.Price != 270 || product.Code != "L1215" { if product.Price != 320 || product.Code != "L1215" {
t.Errorf("invalid data after update, got %+v", product) t.Errorf("invalid data after update, got %+v", product)
} }
DB.Model(&product).Session(&gorm.Session{SkipHooks: true}).Updates(Product3{Code: "L1216"}) DB.Model(&product).Session(&gorm.Session{SkipHooks: true}).Updates(Product3{Code: "L1216"})
if product.Price != 270 || product.Code != "L1216" { if product.Price != 320 || product.Code != "L1216" {
t.Errorf("invalid data after update, got %+v", product) t.Errorf("invalid data after update, got %+v", product)
} }