guregu / dynamo

expressive DynamoDB library for Go
Other
1.3k stars 179 forks source link

Panic on saving struct with pointer to anonymous struct #233

Closed nightlord189 closed 3 months ago

nightlord189 commented 4 months ago

In 1.22.3 if you try to save struct with nil pointer to anonymous struct you got error "panic: reflect: call of reflect.Value.Field on zero Value":

package main

import (
    "fmt"
    "github.com/aws/aws-sdk-go/aws"
    "github.com/aws/aws-sdk-go/aws/session"
    "github.com/guregu/dynamo"
)

type User struct {
    ID *string `dynamo:"id,hash"`
    *Address
}

type Address struct {
    City   string
    Street string
}

func main() {
    sess := session.Must(session.NewSession())
    cli := dynamo.New(sess, &aws.Config{Region: aws.String("eu-west-1")})
    table := cli.Table("bug-save-anonymous")

    id := "1"

    user := User{
        ID:      &id,
        Address: nil,
    }
    err := table.Put(&user).Run()

    fmt.Println("save error:", err)
}
guregu commented 4 months ago

Thanks for the report, I'll take a look

guregu commented 4 months ago

I can get a quick fix in but curious about one detail: at the moment it will always allocate the embedded struct during decoding, so:

User{Address: nil} 
// decodes to:
User{Address: new(Address)}

Not sure how this used to work, maybe ideally it should only allocate if any of its members exist?

guregu commented 4 months ago

I checked an older version before the encoding changes and it has the same behavior, so I'll release the fix now. Will investigate further.

guregu commented 4 months ago

Just released a fix, v1.23.0

nightlord189 commented 4 months ago

Yes, it was fixed. Thank you, @guregu!