From 5cf7fa978d14607b65534f96999167af3f121a8f Mon Sep 17 00:00:00 2001 From: Nddtfjiang Date: Tue, 2 Aug 2022 16:09:11 +0000 Subject: [PATCH] fix: fix walk fields not filter struct Add TestWalkFields Fix WalkFileds lost to filter the struct. Nddtfjiang --- utils/structfield.go | 23 ++++++++++++++------- utils/structfield_test.go | 43 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 7 deletions(-) create mode 100644 utils/structfield_test.go diff --git a/utils/structfield.go b/utils/structfield.go index 9fa8d7cf9de..4ab4d5b6664 100644 --- a/utils/structfield.go +++ b/utils/structfield.go @@ -26,17 +26,26 @@ func WalkFields(t reflect.Type, filter func(field *reflect.StructField) bool) (f if t.Kind() == reflect.Ptr { t = t.Elem() } - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - if field.Type.Kind() == reflect.Struct { - f = append(f, WalkFields(field.Type, filter)...) - } else { - if filter == nil { + + if filter == nil { + for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + if field.Type.Kind() == reflect.Struct { + f = append(f, WalkFields(field.Type, filter)...) + } else { f = append(f, field) - } else if filter(&field) { + } + } + } else { + for i := 0; i < t.NumField(); i++ { + field := t.Field(i) + if filter(&field) { f = append(f, field) + } else if field.Type.Kind() == reflect.Struct { + f = append(f, WalkFields(field.Type, filter)...) } } } + return f } diff --git a/utils/structfield_test.go b/utils/structfield_test.go new file mode 100644 index 00000000000..181ba6d7444 --- /dev/null +++ b/utils/structfield_test.go @@ -0,0 +1,43 @@ +/* +Licensed to the Apache Software Foundation (ASF) under one or more +contributor license agreements. See the NOTICE file distributed with +this work for additional information regarding copyright ownership. +The ASF licenses this file to You under the Apache License, Version 2.0 +(the "License"); you may not use this file except in compliance with +the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package utils + +import ( + "reflect" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +type TestStructForWalkFields struct { + ID string `gorm:"primaryKey"` + Time time.Time `gorm:"primaryKey"` + Data string +} + +// TestWalkFields test the WalkFields +func TestWalkFields(t *testing.T) { + fs := WalkFields(reflect.TypeOf(TestStructForWalkFields{}), func(field *reflect.StructField) bool { + return strings.Contains(strings.ToLower(field.Tag.Get("gorm")), "primarykey") + }) + + assert.Equal(t, fs[0].Name, "ID") + assert.Equal(t, fs[1].Name, "Time") +}