-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmapper.go
202 lines (161 loc) · 4.77 KB
/
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
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package pgkit
import (
"fmt"
"reflect"
"sort"
"strings"
sq "github.com/Masterminds/squirrel"
"github.com/goware/pgkit/v2/internal/reflectx"
)
const (
dbTagName = `db`
dbTagPrefix = `db:"`
)
var Mapper = reflectx.NewMapper(dbTagName)
var (
defaultMapOptions = MapOptions{
IncludeZeroed: false,
IncludeNil: false,
}
sqlDefault = sq.Expr("DEFAULT")
// sqlNULL = sq.Expr("NULL")
ErrExpectingPointerToEitherMapOrStruct = fmt.Errorf(`expecting a pointer to either a map or a struct`)
)
type MapOptions struct {
IncludeZeroed bool
IncludeNil bool
}
// Map converts a struct object (aka record) to a mapping of column names and values
// which can be directly passed to a query executor. This allows you to use structs/objects
// to build easy insert/update queries without having to specify the column names manually.
// The mapper works by reading the column names from a struct fields `db:""` struct tag.
// If you specify `,omitempty` as a tag option, then it will omit the column from the list,
// which allows the database to take over and use its default value.
func Map(record interface{}) ([]string, []interface{}, error) {
return MapWithOptions(record, nil)
}
func MapWithOptions(record interface{}, options *MapOptions) ([]string, []interface{}, error) {
var fv fieldValue
if options == nil {
options = &defaultMapOptions
}
recordV := reflect.ValueOf(record)
if !recordV.IsValid() {
return nil, nil, nil
}
recordT := recordV.Type()
if recordT.Kind() == reflect.Ptr {
// Single dereference. Just in case the user passes a pointer to struct
// instead of a struct.
record = recordV.Elem().Interface()
recordV = reflect.ValueOf(record)
recordT = recordV.Type()
}
// TODO: for the same "type", we can cache the fieldinfo, etc. as it will be the same
// on subsequent loads
switch recordT.Kind() {
case reflect.Struct:
fieldMap := Mapper.TypeMap(recordT).Names
nfields := len(fieldMap)
fv.values = make([]interface{}, 0, nfields)
fv.fields = make([]string, 0, nfields)
for _, fi := range fieldMap {
// Skip any fields which do not specify the `db:".."` tag
if strings.Index(string(fi.Field.Tag), dbTagPrefix) < 0 {
continue
}
// Field options
_, tagOmitEmpty := fi.Options["omitempty"]
fld := reflectx.FieldByIndexesReadOnly(recordV, fi.Index)
if fld.Kind() == reflect.Ptr && fld.IsNil() {
if tagOmitEmpty && !options.IncludeNil {
continue
}
fv.fields = append(fv.fields, fi.Name)
if tagOmitEmpty {
fv.values = append(fv.values, sqlDefault)
} else {
fv.values = append(fv.values, nil)
}
continue
}
value := fld.Interface()
isZero := false
if t, ok := fld.Interface().(hasIsZero); ok {
if t.IsZero() {
isZero = true
}
} else if fld.Kind() == reflect.Array || fld.Kind() == reflect.Slice {
if fld.Len() == 0 {
isZero = true
}
} else if reflect.DeepEqual(fi.Zero.Interface(), value) {
isZero = true
}
if isZero && tagOmitEmpty && !options.IncludeZeroed {
continue
}
fv.fields = append(fv.fields, fi.Name)
// v, err := marshal(value)
// if err != nil {
// return nil, nil, err
// }
v := value
if isZero && tagOmitEmpty {
v = sqlDefault
}
fv.values = append(fv.values, v)
}
case reflect.Map:
nfields := recordV.Len()
fv.values = make([]interface{}, nfields)
fv.fields = make([]string, nfields)
mkeys := recordV.MapKeys()
for i, keyV := range mkeys {
valv := recordV.MapIndex(keyV)
fv.fields[i] = fmt.Sprintf("%v", keyV.Interface())
// v, err := marshal(valv.Interface())
// if err != nil {
// return nil, nil, err
// }
v := valv
fv.values[i] = v
}
default:
return nil, nil, ErrExpectingPointerToEitherMapOrStruct
}
// sanity check -- we must have equal number of columns and values
if len(fv.fields) != len(fv.values) {
return fv.fields, fv.values, fmt.Errorf("record mapper returned %d columns and %d values", len(fv.fields), len(fv.values))
}
// normalize order for better cache hits
sort.Sort(&fv)
return fv.fields, fv.values, nil
}
type fieldValue struct {
fields []string
values []interface{}
}
func (fv *fieldValue) Len() int {
return len(fv.fields)
}
func (fv *fieldValue) Swap(i, j int) {
fv.fields[i], fv.fields[j] = fv.fields[j], fv.fields[i]
fv.values[i], fv.values[j] = fv.values[j], fv.values[i]
}
func (fv *fieldValue) Less(i, j int) bool {
return fv.fields[i] < fv.fields[j]
}
type hasIsZero interface {
IsZero() bool
}
// func marshal(v interface{}) (interface{}, error) {
// // TODO: review db.Marshaler, we may want to keep this too, etc......
// // if m, isMarshaler := v.(db.Marshaler); isMarshaler {
// // var err error
// // if v, err = m.MarshalDB(); err != nil {
// // return nil, err
// // }
// // }
// return v, nil
// }