/
mapper.go
235 lines (204 loc) · 5.06 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package entity
import (
"reflect"
"runtime"
"sync"
"github.com/bww/go-dbx/v1"
"github.com/jmoiron/sqlx/reflectx"
)
const Tag = "db"
const (
optionPrimaryKey = "pk"
optionOmitEmpty = "omitempty"
)
var (
initOnce sync.Once
defaultMapper *FieldMapper
)
func DefaultFieldMapper() *FieldMapper {
initOnce.Do(func() {
defaultMapper = NewFieldMapper()
})
return defaultMapper
}
type FieldMapper struct {
*reflectx.Mapper
}
func NewFieldMapper() *FieldMapper {
return &FieldMapper{
Mapper: reflectx.NewMapperFunc(Tag, ignoreField),
}
}
func (m *FieldMapper) KeysForType(typ reflect.Type) []string {
var cols []string
x := m.TypeMap(typ)
for k, f := range x.Names {
if isExplicitMapping(f) {
if f.Options != nil {
if _, ok := f.Options[optionPrimaryKey]; ok {
cols = append(cols, k)
}
}
}
}
return cols
}
func (m *FieldMapper) Keys(entity interface{}) (*Values, error) {
var kcols []string
var kvals []reflect.Value
e := reflect.ValueOf(entity)
x := m.TypeMap(e.Type())
if e.Kind() != reflect.Ptr {
return nil, dbx.ErrNotAPointer
}
for k, f := range x.Names {
if isExplicitMapping(f) {
if f.Options != nil {
if _, ok := f.Options[optionPrimaryKey]; ok {
kcols = append(kcols, k)
kvals = append(kvals, FieldByIndexes(e, f.Index))
}
}
}
}
return &Values{kcols, kvals}, nil
}
func (m *FieldMapper) ColumnsForType(typ reflect.Type) []string {
var cols []string
x := m.TypeMap(typ)
for k, f := range x.Names {
if isExplicitMapping(f) {
cols = append(cols, k)
}
}
return cols
}
func (m *FieldMapper) Columns(entity interface{}) (*Columns, *Columns) {
var vcols, kcols []string
var vvals, kvals []interface{}
e := reflect.ValueOf(entity)
x := m.TypeMap(e.Type())
for k, f := range x.Names {
if isExplicitMapping(f) {
var x interface{}
v, ok := FieldByIndexesRO(e, f.Index)
if !ok { // the field could not be fully traversed; an intermediate value is nil
vcols, vvals = append(vcols, k), append(vvals, nil)
continue
}
if v.IsValid() && v.CanInterface() {
x = v.Interface()
} else {
x = f.Zero.Interface()
}
vcols = append(vcols, k)
if f.Options == nil {
vvals = append(vvals, x)
} else if _, ok := f.Options[optionOmitEmpty]; ok && isEmptyValue(x, v) {
vvals = append(vvals, nil)
} else {
vvals = append(vvals, x)
}
if f.Options != nil {
if _, ok := f.Options[optionPrimaryKey]; ok {
kcols, kvals = append(kcols, k), append(kvals, x)
}
}
}
}
return &Columns{kcols, kvals}, &Columns{vcols, vvals}
}
// TraversalsByName returns a slice of int slices which represent the struct
// traversals for each mapped name and a slice of bools which indicates whether
// each such traversal is omit-empty. Panics if t is not a struct or Indirectable
// to a struct. Returns empty int slice for each name not found.
func (m *FieldMapper) TraversalsByName(t reflect.Type, names []string) ([][]int, []bool) {
r := make([][]int, 0, len(names))
o := make([]bool, 0, len(names))
m.TraversalsByNameFunc(t, names, func(_ int, i []int, e bool) error {
if i == nil {
r = append(r, []int{})
} else {
r = append(r, i)
}
o = append(o, e)
return nil
})
return r, o
}
// TraversalsByNameFunc traverses the mapped names and calls fn with the index of
// each name and the struct traversal represented by that name. Panics if t is not
// a struct or Indirectable to a struct. Returns the first error returned by fn or nil.
func (m *FieldMapper) TraversalsByNameFunc(t reflect.Type, names []string, fn func(int, []int, bool) error) error {
t = reflectx.Deref(t)
err := mustBe(t, reflect.Struct)
if err != nil {
return err
}
tm := m.TypeMap(t)
for i, name := range names {
fi, ok := tm.Names[name]
if !ok {
if err := fn(i, nil, false); err != nil {
return err
}
} else {
var oe bool
if fi.Options != nil {
_, oe = fi.Options[optionOmitEmpty]
}
if err := fn(i, fi.Index, oe); err != nil {
return err
}
}
}
return nil
}
func FieldByIndexes(v reflect.Value, indexes []int) reflect.Value {
for _, x := range indexes {
v = reflect.Indirect(v).Field(x)
if v.Kind() == reflect.Ptr && v.IsNil() {
v.Set(reflect.New(reflectx.Deref(v.Type())))
}
if v.Kind() == reflect.Map && v.IsNil() {
v.Set(reflect.MakeMap(v.Type()))
}
}
return v
}
func FieldByIndexesRO(v reflect.Value, indexes []int) (reflect.Value, bool) {
for _, i := range indexes {
v = reflect.Indirect(v)
if v.IsValid() {
v = v.Field(i)
} else {
return v, false
}
}
return v, true
}
type kinder interface {
Kind() reflect.Kind
}
func mustBe(v kinder, expected reflect.Kind) error {
if k := v.Kind(); k != expected {
return &reflect.ValueError{Method: methodName(), Kind: k}
}
return nil
}
func methodName() string {
pc, _, _, _ := runtime.Caller(2)
f := runtime.FuncForPC(pc)
if f != nil {
return f.Name()
} else {
return "unknown method"
}
}
const ignoreName = "__ignore_field__"
func ignoreField(n string) string {
return ignoreName
}
func isExplicitMapping(f *reflectx.FieldInfo) bool {
return f.Name != ignoreName
}