-
Notifications
You must be signed in to change notification settings - Fork 1
/
encode.go
75 lines (64 loc) · 1.78 KB
/
encode.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
69
70
71
72
73
74
75
package bq
import (
"fmt"
"reflect"
"time"
"google.golang.org/api/bigquery/v2"
)
// Encode takes a struct and returns a BigQuery compatible encoded map for the
// legacy BigQuery library.
func EncodeLegacy(v interface{}, omitEmpty bool) (map[string]bigquery.JsonValue, error) {
value := reflect.ValueOf(v)
if value.Kind() != reflect.Struct {
if value.Kind() == reflect.Ptr {
return EncodeLegacy(value.Elem().Interface(), omitEmpty)
}
return nil, fmt.Errorf("bigquery: unsupported type: %T (%v)", v, value.Kind())
}
m := make(map[string]bigquery.JsonValue)
valueType := value.Type()
for i := 0; i < valueType.NumField(); i++ {
field := valueType.Field(i)
fieldValue := value.Field(i)
name := fieldInfo(field)
switch {
case !fieldValue.CanInterface(), name == "-":
continue
}
var fieldValueInterface interface{}
if fieldValue.Kind() == reflect.Ptr {
if fieldValue.IsNil() {
fieldValueInterface = nil
} else {
fieldValueInterface = fieldValue.Elem().Interface()
}
} else {
fieldValueInterface = fieldValue.Interface()
}
if fieldValue.Kind() == reflect.Struct && fieldValue.Type() != reflect.TypeOf(time.Time{}) {
if mm, err := EncodeLegacy(fieldValueInterface, omitEmpty); err == nil {
// The fields of an embedded struct gets added directly to the map here
if field.Anonymous {
for k, v := range mm {
m[k] = v
}
} else {
m[name] = mm
}
}
} else {
if !(omitEmpty &&
(fieldValueInterface == reflect.Zero(fieldValue.Type()).Interface() ||
fieldValueInterface == nil)) {
m[name] = bigquery.JsonValue(fieldValueInterface)
}
}
}
return m, nil
}
func fieldInfo(field reflect.StructField) string {
if tag := field.Tag.Get("bigquery"); tag != "" {
return tag
}
return field.Name
}