Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow named structs to be embedded #303

Merged
merged 3 commits into from Jul 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this still true to provide backwards compatibility?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

anonymous struct is basically an embedded struct, so I think no problem

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