Skip to content

Commit

Permalink
Allowing ScanStructs to take a struct with an embedded pointer to a s…
Browse files Browse the repository at this point in the history
…truck.
  • Loading branch information
andymoon committed Aug 25, 2015
1 parent 18ccf13 commit 96ece5b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
25 changes: 21 additions & 4 deletions crud_exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ func assignVals(i interface{}, results []Record, cm columnMap) error {
val := reflect.Indirect(reflect.ValueOf(i))
t, _, isSliceOfPointers := getTypeInfo(i, val)
switch val.Kind() {
case reflect.Struct:
case reflect.Struct:
result := results[0]
for name, data := range cm {
src, ok := result[name]
Expand All @@ -234,9 +234,10 @@ func assignVals(i interface{}, results []Record, cm columnMap) error {
}
}
}
case reflect.Slice:
case reflect.Slice:
for _, result := range results {
row := reflect.Indirect(reflect.New(t))
initEmbeddedPtr(row)
for name, data := range cm {
src, ok := result[name]
if ok {
Expand All @@ -259,6 +260,18 @@ func assignVals(i interface{}, results []Record, cm columnMap) error {
return nil
}

func initEmbeddedPtr(value reflect.Value) {
for i := 0; i < value.NumField(); i++ {
v := value.Field(i)
kind := v.Kind()
t := value.Type().Field(i)
if t.Anonymous && kind == reflect.Ptr {
z := reflect.New(t.Type.Elem())
v.Set(z)
}
}
}

func getColumnMap(i interface{}) (columnMap, error) {
val := reflect.Indirect(reflect.ValueOf(i))
t, valKind, _ := getTypeInfo(i, val)
Expand All @@ -276,8 +289,12 @@ func createColumnMap(t reflect.Type) columnMap {
var subColMaps []columnMap
for i := 0; i < n; i++ {
f := t.Field(i)
if f.Anonymous && f.Type.Kind() == reflect.Struct {
subColMaps = append(subColMaps, createColumnMap(f.Type))
if f.Anonymous && (f.Type.Kind() == reflect.Struct || f.Type.Kind() == reflect.Ptr) {
if f.Type.Kind() == reflect.Ptr {
subColMaps = append(subColMaps, createColumnMap(f.Type.Elem()))
} else {
subColMaps = append(subColMaps, createColumnMap(f.Type))
}
} else {
columnName := f.Tag.Get("db")
if columnName == "" {
Expand Down
9 changes: 0 additions & 9 deletions dataset.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,15 +290,6 @@ func (me *Dataset) expressionSql(buf *SqlBuilder, expression Expression) error {
return NewGoquError("Unsupported expression type %T", expression)
}

func (me *Dataset) isValueNil(value reflect.Value, kind reflect.Kind) bool {
switch kind {
case reflect.Ptr, reflect.Interface:
return value.IsNil()
default:
return false
}
}

func (me *Dataset) isSpecialType(value reflect.Value) bool {
i := value.Interface()
if _, ok := i.(time.Time); ok {
Expand Down

0 comments on commit 96ece5b

Please sign in to comment.