-
Notifications
You must be signed in to change notification settings - Fork 62
/
struct_mapping.go
51 lines (43 loc) · 1.22 KB
/
struct_mapping.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
package dat
import (
"fmt"
"reflect"
"github.com/mgutz/str"
"gopkg.in/mgutz/dat.v1/reflectx"
)
var fieldMapper = reflectx.NewMapperTagFunc("db", nil, nil)
// reflectFields gets a cached field information about record
func reflectFields(rec interface{}) *reflectx.StructMap {
val := reflect.Indirect(reflect.ValueOf(rec))
vtype := val.Type()
return fieldMapper.TypeMap(vtype)
}
// ValuesFor ...
func valuesFor(recordType reflect.Type, record reflect.Value, columns []string) ([]interface{}, error) {
vals := fieldMapper.FieldsByName(record, columns)
values := make([]interface{}, len(columns))
for i, val := range vals {
if !val.IsValid() {
return nil, fmt.Errorf("Could not find struct tag in type %s: `db:\"%s\"`", recordType.Name(), columns[i])
}
values[i] = val.Interface()
}
return values, nil
}
func reflectColumns(v interface{}) []string {
cols := []string{}
for _, name := range reflectFields(v).DeclaredNames {
cols = append(cols, name)
}
return cols
}
func reflectExcludeColumns(v interface{}, blacklist []string) []string {
cols := []string{}
for _, name := range reflectFields(v).DeclaredNames {
if str.SliceContains(blacklist, name) {
continue
}
cols = append(cols, name)
}
return cols
}