-
Notifications
You must be signed in to change notification settings - Fork 3
/
common.go
163 lines (147 loc) · 5.29 KB
/
common.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package dbw
import (
"fmt"
"reflect"
"strings"
"gorm.io/gorm"
)
// UpdateFields will create a map[string]interface of the update values to be
// sent to the db. The map keys will be the field names for the fields to be
// updated. The caller provided fieldMaskPaths and setToNullPaths must not
// intersect. fieldMaskPaths and setToNullPaths cannot both be zero len.
func UpdateFields(i interface{}, fieldMaskPaths []string, setToNullPaths []string) (map[string]interface{}, error) {
const op = "dbw.UpdateFields"
if i == nil {
return nil, fmt.Errorf("%s: interface is missing: %w", op, ErrInvalidParameter)
}
if fieldMaskPaths == nil {
fieldMaskPaths = []string{}
}
if setToNullPaths == nil {
setToNullPaths = []string{}
}
if len(fieldMaskPaths) == 0 && len(setToNullPaths) == 0 {
return nil, fmt.Errorf("%s: both fieldMaskPaths and setToNullPaths are zero len: %w", op, ErrInvalidParameter)
}
inter, maskPaths, nullPaths, err := Intersection(fieldMaskPaths, setToNullPaths)
if err != nil {
return nil, fmt.Errorf("%s: %w", op, ErrInvalidParameter)
}
if len(inter) != 0 {
return nil, fmt.Errorf("%s: fieldMashPaths and setToNullPaths cannot intersect: %w", op, ErrInvalidParameter)
}
updateFields := map[string]interface{}{} // case sensitive update fields to values
found := map[string]struct{}{} // we need something to keep track of found fields (case insensitive)
val := reflect.Indirect(reflect.ValueOf(i))
structTyp := val.Type()
for i := 0; i < structTyp.NumField(); i++ {
if f, ok := maskPaths[strings.ToUpper(structTyp.Field(i).Name)]; ok {
updateFields[f] = val.Field(i).Interface()
found[strings.ToUpper(f)] = struct{}{}
continue
}
if f, ok := nullPaths[strings.ToUpper(structTyp.Field(i).Name)]; ok {
updateFields[f] = gorm.Expr("NULL")
found[strings.ToUpper(f)] = struct{}{}
continue
}
kind := structTyp.Field(i).Type.Kind()
if kind == reflect.Struct || kind == reflect.Ptr {
embType := structTyp.Field(i).Type
// check if the embedded field is exported via CanInterface()
if val.Field(i).CanInterface() {
embVal := reflect.Indirect(reflect.ValueOf(val.Field(i).Interface()))
// if it's a ptr to a struct, then we need a few more bits before proceeding.
if kind == reflect.Ptr {
embVal = val.Field(i).Elem()
if !embVal.IsValid() {
continue
}
embType = embVal.Type()
if embType.Kind() != reflect.Struct {
continue
}
}
for embFieldNum := 0; embFieldNum < embType.NumField(); embFieldNum++ {
if f, ok := maskPaths[strings.ToUpper(embType.Field(embFieldNum).Name)]; ok {
updateFields[f] = embVal.Field(embFieldNum).Interface()
found[strings.ToUpper(f)] = struct{}{}
}
if f, ok := nullPaths[strings.ToUpper(embType.Field(embFieldNum).Name)]; ok {
updateFields[f] = gorm.Expr("NULL")
found[strings.ToUpper(f)] = struct{}{}
}
}
continue
}
}
}
if missing := findMissingPaths(setToNullPaths, found); len(missing) != 0 {
return nil, fmt.Errorf("%s: null paths not found in resource: %s: %w", op, missing, ErrInvalidParameter)
}
if missing := findMissingPaths(fieldMaskPaths, found); len(missing) != 0 {
return nil, fmt.Errorf("%s: field mask paths not found in resource: %s: %w", op, missing, ErrInvalidParameter)
}
return updateFields, nil
}
func findMissingPaths(paths []string, foundPaths map[string]struct{}) []string {
notFound := []string{}
for _, f := range paths {
if _, ok := foundPaths[strings.ToUpper(f)]; !ok {
notFound = append(notFound, f)
}
}
return notFound
}
// Intersection is a case-insensitive search for intersecting values. Returns
// []string of the Intersection with values in lowercase, and map[string]string
// of the original av and bv, with the key set to uppercase and value set to the
// original
func Intersection(av, bv []string) ([]string, map[string]string, map[string]string, error) {
const op = "dbw.Intersection"
if av == nil {
return nil, nil, nil, fmt.Errorf("%s: av is missing: %w", op, ErrInvalidParameter)
}
if bv == nil {
return nil, nil, nil, fmt.Errorf("%s: bv is missing: %w", op, ErrInvalidParameter)
}
if len(av) == 0 && len(bv) == 0 {
return []string{}, map[string]string{}, map[string]string{}, nil
}
s := []string{}
ah := map[string]string{}
bh := map[string]string{}
for i := 0; i < len(av); i++ {
ah[strings.ToUpper(av[i])] = av[i]
}
for i := 0; i < len(bv); i++ {
k := strings.ToUpper(bv[i])
bh[k] = bv[i]
if _, found := ah[k]; found {
s = append(s, strings.ToLower(bh[k]))
}
}
return s, ah, bh, nil
}
// BuildUpdatePaths takes a map of field names to field values, field masks,
// fields allowed to be zero value, and returns both a list of field names to
// update and a list of field names that should be set to null.
func BuildUpdatePaths(fieldValues map[string]interface{}, fieldMask []string, allowZeroFields []string) (masks []string, nulls []string) {
for f, v := range fieldValues {
if !contains(fieldMask, f) {
continue
}
switch {
case isZero(v) && !contains(allowZeroFields, f):
nulls = append(nulls, f)
default:
masks = append(masks, f)
}
}
return masks, nulls
}
func isZero(i interface{}) bool {
return i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface())
}