Skip to content

Commit

Permalink
Merge pull request jmoiron#429 from snigle/reflectx
Browse files Browse the repository at this point in the history
fix reflectx dominant field
  • Loading branch information
jmoiron authored Jan 24, 2021
2 parents d5886a9 + d456884 commit 29f9f5e
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 5 deletions.
11 changes: 8 additions & 3 deletions reflectx/reflect.go
Original file line number Diff line number Diff line change
Expand Up @@ -429,9 +429,14 @@ QueueLoop:

flds := &StructMap{Index: m, Tree: root, Paths: map[string]*FieldInfo{}, Names: map[string]*FieldInfo{}}
for _, fi := range flds.Index {
flds.Paths[fi.Path] = fi
if fi.Name != "" && !fi.Embedded {
flds.Names[fi.Path] = fi
// check if nothing has already been pushed with the same path
// sometimes you can choose to override a type using embedded struct
fld, ok := flds.Paths[fi.Path]
if !ok || fld.Embedded {
flds.Paths[fi.Path] = fi
if fi.Name != "" && !fi.Embedded {
flds.Names[fi.Path] = fi
}
}
}

Expand Down
43 changes: 41 additions & 2 deletions reflectx/reflect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,13 +141,52 @@ func TestBasicEmbeddedWithTags(t *testing.T) {
// }

v := m.FieldByName(zv, "a")
if ival(v) != z.Bar.Foo.A { // the dominant field
t.Errorf("Expecting %d, got %d", z.Bar.Foo.A, ival(v))
if ival(v) != z.A { // the dominant field
t.Errorf("Expecting %d, got %d", z.A, ival(v))
}
v = m.FieldByName(zv, "b")
if ival(v) != z.B {
t.Errorf("Expecting %d, got %d", z.B, ival(v))
}
}

func TestBasicEmbeddedWithSameName(t *testing.T) {
type Foo struct {
A int `db:"a"`
Foo int `db:"Foo"` // Same name as the embedded struct
}

type FooExt struct {
Foo
B int `db:"b"`
}

m := NewMapper("db")

z := FooExt{}
z.A = 1
z.B = 2
z.Foo.Foo = 3

zv := reflect.ValueOf(z)
fields := m.TypeMap(reflect.TypeOf(z))

if len(fields.Index) != 4 {
t.Errorf("Expecting 3 fields, found %d", len(fields.Index))
}

v := m.FieldByName(zv, "a")
if ival(v) != z.A { // the dominant field
t.Errorf("Expecting %d, got %d", z.A, ival(v))
}
v = m.FieldByName(zv, "b")
if ival(v) != z.B {
t.Errorf("Expecting %d, got %d", z.B, ival(v))
}
v = m.FieldByName(zv, "Foo")
if ival(v) != z.Foo.Foo {
t.Errorf("Expecting %d, got %d", z.Foo.Foo, ival(v))
}
}

func TestFlatTags(t *testing.T) {
Expand Down

0 comments on commit 29f9f5e

Please sign in to comment.