From eeee014500669387fb0442ebbed1556a04bad8c5 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sat, 27 Jun 2020 08:04:12 +0800 Subject: [PATCH] Only query with readable fields --- statement.go | 24 ++++++++++++++---------- tests/customize_field_test.go | 8 ++++++++ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/statement.go b/statement.go index 7cc01bb8..e902b739 100644 --- a/statement.go +++ b/statement.go @@ -271,22 +271,26 @@ func (stmt *Statement) BuildCondition(query interface{}, args ...interface{}) (c switch reflectValue.Kind() { case reflect.Struct: for _, field := range s.Fields { - if v, isZero := field.ValueOf(reflectValue); !isZero { - if field.DBName == "" { - conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.Name}, Value: v}) - } else { - conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.DBName}, Value: v}) + if field.Readable { + if v, isZero := field.ValueOf(reflectValue); !isZero { + if field.DBName == "" { + conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.Name}, Value: v}) + } else { + conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.DBName}, Value: v}) + } } } } case reflect.Slice, reflect.Array: for i := 0; i < reflectValue.Len(); i++ { for _, field := range s.Fields { - if v, isZero := field.ValueOf(reflectValue.Index(i)); !isZero { - if field.DBName == "" { - conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.Name}, Value: v}) - } else { - conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.DBName}, Value: v}) + if field.Readable { + if v, isZero := field.ValueOf(reflectValue.Index(i)); !isZero { + if field.DBName == "" { + conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.Name}, Value: v}) + } else { + conds = append(conds, clause.Eq{Column: clause.Column{Table: s.Table, Name: field.DBName}, Value: v}) + } } } } diff --git a/tests/customize_field_test.go b/tests/customize_field_test.go index 910fa6ae..9c6ab948 100644 --- a/tests/customize_field_test.go +++ b/tests/customize_field_test.go @@ -134,10 +134,18 @@ func TestCustomizeField(t *testing.T) { t.Fatalf("invalid updated result: %#v", result2) } + if err := DB.Where(CustomizeFieldStruct{Name: create.Name, FieldReadonly: create.FieldReadonly, FieldIgnore: create.FieldIgnore}).First(&CustomizeFieldStruct{}).Error; err == nil { + t.Fatalf("Should failed to find result") + } + if err := DB.Table("customize_field_structs").Where("1 = 1").UpdateColumn("field_readonly", "readonly").Error; err != nil { t.Fatalf("failed to update field_readonly column") } + if err := DB.Where(CustomizeFieldStruct{Name: create.Name, FieldReadonly: "readonly", FieldIgnore: create.FieldIgnore}).First(&CustomizeFieldStruct{}).Error; err != nil { + t.Fatalf("Should find result") + } + var result3 CustomizeFieldStruct DB.Find(&result3, "name = ?", "create")