Skip to content

Commit

Permalink
Allow named structs to be embedded (#303)
Browse files Browse the repository at this point in the history
* Allow named structs to be embedded

* Fix name issue

* Replace loop with HasSuffix
  • Loading branch information
dranikpg committed Jul 5, 2022
1 parent d417e5f commit 36bf6b0
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
13 changes: 12 additions & 1 deletion document_meta.go
Expand Up @@ -238,7 +238,7 @@ func getDocumentMeta(rt reflect.Type, skipAssoc bool) DocumentMeta {
typ = typ.Elem()
}

if typ.Kind() == reflect.Struct && sf.Anonymous {
if typ.Kind() == reflect.Struct && isEmbedded(sf) {
embedded := getDocumentMeta(typ, skipAssoc)
embeddedName := ""
if tagged {
Expand Down Expand Up @@ -357,6 +357,17 @@ func fieldName(sf reflect.StructField) (string, bool) {
return snaker.CamelToSnake(sf.Name), false
}

func isEmbedded(sf reflect.StructField) bool {
// anonymous structs are always embedded
if sf.Anonymous {
return true
}
if tag := sf.Tag.Get("db"); strings.HasSuffix(tag, ",embedded") {
return true
}
return false
}

func searchPrimary(rt reflect.Type) ([]string, [][]int) {
if result, cached := primariesCache.Load(rt); cached {
p := result.(primaryData)
Expand Down
28 changes: 28 additions & 0 deletions document_test.go
Expand Up @@ -234,6 +234,34 @@ func TestDocument_IndexEmbedded(t *testing.T) {
assert.Equal(t, index, doc.Index())
}

func TestDocument_IndexFieldEmbedded(t *testing.T) {
type FirstEmbedded struct {
A int
B int
}
type SecondEmbedded struct {
D float32
}
var (
record = struct {
First FirstEmbedded `db:"first_,embedded"`
C string
Second SecondEmbedded `db:",embedded"`
E int `db:"embedded"` // this field is not embedded, but only called so
}{}
doc = NewDocument(&record)
index = map[string][]int{
"first_a": {0, 0},
"first_b": {0, 1},
"c": {1},
"d": {2, 0},
"embedded": {3},
}
)

assert.Equal(t, index, doc.Index())
}

func TestDocument_EmbeddedNameConfict(t *testing.T) {
type Embedded struct {
Name string
Expand Down

0 comments on commit 36bf6b0

Please sign in to comment.