georgysavva / scany

Library for scanning data from a database into Go structs and more
MIT License
1.27k stars 67 forks source link

Nested/Embeded structs don't seem to work correctly #34

Closed krazik-intuit closed 3 years ago

krazik-intuit commented 3 years ago

I'm trying to switch from sqlx, I have nested structs for commonly used fields, these worked with sqlx. you seem to have a function initializeNested() but it's called after the error, so not sure if it doesn't work or for something else?

error scany: column: 'id': no corresponding field found, or it's unexported in...

type AutoIncrIDField struct {
    ID uint32 `db:"id,primarykey,autoincrement" json:"id,omitempty"`
}
type Another struct {
    AutoIncrIDField
        SomeOtherID     uint32      `db:"some_other_id"`
}

I tried to poke around to see where to fix but not quite sure. Usually you need to recurse into the child structs.

From another part of my code where I do this

func sqlMockFieldsFromStruct(inputStruct interface{}) []sqlMockField {
    result := []sqlMockField{}
    structValue := reflect.ValueOf(inputStructValue)
    structType := reflect.TypeOf(inputStructValue)

    for i := 0; i < structType.NumField(); i++ {
        fieldValue := structValue.Field(i)
        if structType.Field(i).Anonymous { // <<-- HERE
            result = append(result, sqlMockFieldsFromStruct(fieldValue.Interface())...)
        } else {
            result = append(result, sqlMockField{
                Field: structType.Field(i),
                Value: fieldValue,
            })
        }
    }
    return result
}
krazik-intuit commented 3 years ago

Also thank you for building this!

krazik-intuit commented 3 years ago

turns out this was the , in the tag. I've removed them since scany doesn't use.

georgysavva commented 3 years ago

Hi! Yes, scany doesn't support any , in the struct tag for now.

krazik-intuit commented 3 years ago

@georgysavva it's super simple to add support for tho. I'm opening a PR should you want it.