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

Allocate struct pointers fields with "bind" tag #1165

Merged
merged 1 commit into from Dec 14, 2022
Merged
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
23 changes: 22 additions & 1 deletion queries/reflect.go
Expand Up @@ -251,7 +251,7 @@ Rows:
case kindSliceStruct:
pointers = PtrsFromMapping(oneStruct, mapping)
case kindPtrSliceStruct:
newStruct = reflect.New(structType)
newStruct = makeStructPtr(structType)
pointers = PtrsFromMapping(reflect.Indirect(newStruct), mapping)
}
if err != nil {
Expand Down Expand Up @@ -279,6 +279,27 @@ Rows:
return nil
}

// makeStructPtr takes a struct type and returns a pointer to a new instance of it. This is used by bind to allocate new
// slice elements when the bound-to variable is []*Struct
func makeStructPtr(typ reflect.Type) reflect.Value {
// Allocate struct
val := reflect.New(typ)

// For all the fields
for i := 0; i < typ.NumField(); i++ {
field := typ.Field(i)
_, recurse := getBoilTag(field)

// If ",bind" was in the tag and the field is a pointer
if recurse && field.Type.Kind() == reflect.Ptr {
// Then allocate the field
val.Elem().Field(i).Set(reflect.New(field.Type.Elem()))
}
}

return val
}

// BindMapping creates a mapping that helps look up the pointer for the
// column given.
func BindMapping(typ reflect.Type, mapping map[string]uint64, cols []string) ([]uint64, error) {
Expand Down