-
Notifications
You must be signed in to change notification settings - Fork 3
/
smart_row_mapper.go
68 lines (56 loc) · 1.35 KB
/
smart_row_mapper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package cypress
import (
"errors"
"reflect"
)
var (
// ErrPointerRequired a pointer is required
ErrPointerRequired = errors.New("a pointer is required")
)
type smartMapper struct {
valueType reflect.Type
}
// NewSmartMapper creates a smart row mapper for data row
func NewSmartMapper(value interface{}) RowMapper {
return &smartMapper{reflect.TypeOf(value)}
}
// Map maps the data row to a value object
func (mapper *smartMapper) Map(row DataRow) (interface{}, error) {
columns, err := row.Columns()
if err != nil {
return nil, err
}
columnTypes, err := row.ColumnTypes()
if err != nil {
return nil, err
}
if len(columnTypes) == 1 {
t := mapper.valueType
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
value := reflect.New(t)
row.Scan(value.Interface())
return value.Elem().Interface(), nil
}
}
valueType := mapper.valueType
if valueType.Kind() != reflect.Ptr {
return nil, ErrPointerRequired
}
valueType = valueType.Elem()
getters := GetFieldValueGetters(valueType)
value := reflect.New(valueType)
values := make([]interface{}, len(columns))
for index, name := range columns {
getter, ok := getters[name]
if ok {
values[index] = getter.Get(value.Elem()).Addr().Interface()
} else {
values[index] = &values[index]
}
}
row.Scan(values...)
return value.Interface(), nil
}