Skip to content

Commit

Permalink
reflect
Browse files Browse the repository at this point in the history
  • Loading branch information
RangelReale committed Jun 7, 2024
1 parent 80b4523 commit e52275c
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 4 deletions.
16 changes: 16 additions & 0 deletions sq/structarg/reflect.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ func (s *argValues) getStructFieldByName(value reflect.Value, fieldName string)
// avoid sending a pointer to a nil
return nil, true
}
if s.derefPointer {
return deref(v), true
}
return v.Interface(), true
}
}
Expand All @@ -72,3 +75,16 @@ func getReflectValue(value any) reflect.Value {
}
return v
}

func deref(v reflect.Value) any {
for {
if v.Kind() == reflect.Ptr {
if v.IsNil() {
return nil
}
v = v.Elem()
} else {
return v.Interface()
}
}
}
59 changes: 58 additions & 1 deletion sq/structarg/reflect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func TestReflect(t *testing.T) {
},
{
name: "O",
expected: 45,
expected: &oval,
},
{
name: "P",
Expand All @@ -79,6 +79,63 @@ func TestReflect(t *testing.T) {
}
}

func TestReflectDeref(t *testing.T) {
type x struct {
H *string
T *string
J **int
L ***int
}

hval := "99"
jval := 11
jval1 := &jval
lval := 45
lval1 := &lval
lval2 := &lval1

value := &x{
H: &hval,
J: &jval1,
L: &lval2,
}

a := New(value, WithDerefPointer(true))

for _, test := range []struct {
name string
expected any
expectedNotFound bool
}{
{
name: "H",
expected: "99",
},
{
name: "T",
expected: nil,
},
{
name: "J",
expected: 11,
},
{
name: "L",
expected: 45,
},
} {
t.Run(test.name, func(t *testing.T) {
v, ok := a.Get(test.name)
if test.expectedNotFound {
assert.Assert(t, !ok)
} else {
assert.Assert(t, ok)
assert.DeepEqual(t, test.expected, v)
}
})
}
}

func TestReflectEmbed(t *testing.T) {
type Xembed struct {
A string
Expand Down
13 changes: 10 additions & 3 deletions sq/structarg/structarg.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@ func New(value any, options ...Option) litsql.ArgValues {
type argValues struct {
value reflect.Value

tagName string
mapperFunc func(string) string
tagName string
derefPointer bool
mapperFunc func(string) string
}

func (s *argValues) Get(name string) (any, bool) {
return s.getStructFieldByName(s.value, name)
}


type Option func(*argValues)

// WithTagName sets the struct tag name to use. Default is "json".
Expand All @@ -44,6 +44,13 @@ func WithTagName(tagName string) Option {
}
}

// WithDerefPointer dereferences pointers in struct field values.
func WithDerefPointer(deref bool) Option {
return func(o *argValues) {
o.derefPointer = deref
}
}

// WithMapperFunc sets the field name mapper function.
func WithMapperFunc(mapperFunc func(string) string) Option {
return func(o *argValues) {
Expand Down

0 comments on commit e52275c

Please sign in to comment.