-
Notifications
You must be signed in to change notification settings - Fork 95
/
scan.go
447 lines (378 loc) · 10.2 KB
/
scan.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
// +build !wasm
package document
import (
"reflect"
"strings"
"time"
"github.com/genjidb/genji/internal/errors"
"github.com/genjidb/genji/internal/stringutil"
"github.com/genjidb/genji/types"
)
// A Scanner can iterate over a document and scan all the fields.
type Scanner interface {
ScanDocument(types.Document) error
}
// Scan each field of the document into the given variables.
func Scan(d types.Document, targets ...interface{}) error {
var i int
return d.Iterate(func(f string, v types.Value) error {
if i >= len(targets) {
return errors.New("target list too small")
}
target := targets[i]
i++
ref := reflect.ValueOf(target)
if !ref.IsValid() {
return &ErrUnsupportedType{target, stringutil.Sprintf("Parameter %d is not valid", i)}
}
return scanValue(v, ref)
})
}
// StructScan scans d into t. t is expected to be a pointer to a struct.
//
// By default, each struct field name is lowercased and the document's GetByField method
// is called with that name. If there is a match, the value is converted to the struct
// field type when possible, otherwise an error is returned.
// The decoding of each struct field can be customized by the format string stored
// under the "genji" key stored in the struct field's tag.
// The content of the format string is used instead of the struct field name and passed
// to the GetByField method.
func StructScan(d types.Document, t interface{}) error {
ref := reflect.ValueOf(t)
if !ref.IsValid() || ref.Kind() != reflect.Ptr {
return errors.New("target must be pointer to a valid Go type")
}
if ref.IsNil() {
ref.Set(reflect.New(ref.Type().Elem()))
}
return structScan(d, ref)
}
func structScan(d types.Document, ref reflect.Value) error {
if ref.Type().Implements(reflect.TypeOf((*Scanner)(nil)).Elem()) {
return ref.Interface().(Scanner).ScanDocument(d)
}
sref := reflect.Indirect(ref)
stp := sref.Type()
l := sref.NumField()
for i := 0; i < l; i++ {
f := sref.Field(i)
sf := stp.Field(i)
var name string
if gtag, ok := sf.Tag.Lookup("genji"); ok {
if gtag == "-" {
continue
}
name = gtag
} else {
name = strings.ToLower(sf.Name)
}
v, err := d.GetByField(name)
if errors.Is(err, ErrFieldNotFound) {
v = types.NewNullValue()
} else if err != nil {
return err
}
if err := scanValue(v, f); err != nil {
return err
}
}
return nil
}
// SliceScan scans a document array into a slice or fixed size array. t must be a pointer
// to a valid slice or array.
//
// It t is a slice pointer and its capacity is too low, a new slice will be allocated.
// Otherwise, its length is set to 0 so that its content is overwritten.
//
// If t is an array pointer, its capacity must be bigger than the length of a, otherwise an error is
// returned.
func SliceScan(a types.Array, t interface{}) error {
return sliceScan(a, reflect.ValueOf(t))
}
func sliceScan(a types.Array, ref reflect.Value) error {
if !ref.IsValid() || ref.Kind() != reflect.Ptr || ref.IsNil() {
return errors.New("target must be pointer to a slice or array")
}
tp := ref.Type()
k := tp.Elem().Kind()
if k != reflect.Array && k != reflect.Slice {
return errors.New("target must be pointer to a slice or array")
}
al, err := ArrayLength(a)
if err != nil {
return err
}
sref := reflect.Indirect(ref)
// if array, make sure it is big enough
if k == reflect.Array && sref.Len() < al {
return errors.New("array length too small")
}
// if slice, reduce its length to 0 to overwrite the buffer
if k == reflect.Slice {
if sref.Cap() < al {
sref.Set(reflect.MakeSlice(tp.Elem(), 0, al))
} else {
sref.SetLen(0)
}
}
stp := sref.Type()
err = a.Iterate(func(i int, v types.Value) error {
if k == reflect.Array {
err := scanValue(v, sref.Index(i).Addr())
if err != nil {
return err
}
} else {
newV := reflect.New(stp.Elem())
err := scanValue(v, newV)
if err != nil {
return err
}
sref = reflect.Append(sref, reflect.Indirect(newV))
}
return nil
})
if err != nil {
return err
}
if k == reflect.Slice {
ref.Elem().Set(sref)
}
return nil
}
// MapScan decodes the document into a map.
func MapScan(d types.Document, t interface{}) error {
ref := reflect.ValueOf(t)
if !ref.IsValid() {
return &ErrUnsupportedType{ref, "t must be a valid reference"}
}
if ref.Kind() == reflect.Ptr {
ref = reflect.Indirect(ref)
}
if ref.Kind() != reflect.Map {
return &ErrUnsupportedType{ref, "t is not a map"}
}
return mapScan(d, ref)
}
func mapScan(d types.Document, ref reflect.Value) error {
if ref.Type().Key().Kind() != reflect.String {
return &ErrUnsupportedType{ref, "map key must be a string"}
}
if ref.IsNil() {
ref.Set(reflect.MakeMap(ref.Type()))
}
return d.Iterate(func(f string, v types.Value) error {
newV := reflect.New(ref.Type().Elem())
err := scanValue(v, newV)
if err != nil {
return err
}
ref.SetMapIndex(reflect.ValueOf(f), newV.Elem())
return nil
})
}
// ScanValue scans v into t.
func ScanValue(v types.Value, t interface{}) error {
return scanValue(v, reflect.ValueOf(t))
}
func scanValue(v types.Value, ref reflect.Value) error {
if !ref.IsValid() {
return &ErrUnsupportedType{ref, "parameter is not a valid reference"}
}
if v.Type() == types.NullValue {
if ref.Type().Kind() != reflect.Ptr {
return nil
}
if ref.IsNil() {
return nil
}
if !ref.CanSet() {
ref = reflect.Indirect(ref)
}
ref.Set(reflect.Zero(ref.Type()))
return nil
}
if ref.Type().Kind() == reflect.Ptr && ref.IsNil() {
ref.Set(reflect.New(ref.Type().Elem()))
}
ref = reflect.Indirect(ref)
// if the user passed a **ptr
// make sure it points to a valid value
// or create one
// then dereference
if ref.Kind() == reflect.Ptr {
if ref.IsNil() {
ref.Set(reflect.New(ref.Type().Elem()))
}
ref = reflect.Indirect(ref)
}
// Scan nulls as Go zero values.
if v.Type() == types.NullValue {
ref.Set(reflect.Zero(ref.Type()))
return nil
}
switch ref.Kind() {
case reflect.String:
v, err := CastAsText(v)
if err != nil {
return err
}
ref.SetString(string(v.V().(string)))
return nil
case reflect.Bool:
v, err := CastAsBool(v)
if err != nil {
return err
}
ref.SetBool(v.V().(bool))
return nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
v, err := CastAsInteger(v)
if err != nil {
return err
}
x := v.V().(int64)
if x < 0 {
return stringutil.Errorf("cannot convert value %d into Go value of type %s", x, ref.Type().Name())
}
ref.SetUint(uint64(x))
return nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
v, err := CastAsInteger(v)
if err != nil {
return err
}
ref.SetInt(v.V().(int64))
return nil
case reflect.Float32, reflect.Float64:
v, err := CastAsDouble(v)
if err != nil {
return err
}
ref.SetFloat(v.V().(float64))
return nil
case reflect.Interface:
switch v.Type() {
case types.DocumentValue:
m := make(map[string]interface{})
vm := reflect.ValueOf(m)
ref.Set(vm)
return mapScan(v.V().(types.Document), vm)
case types.ArrayValue:
var s []interface{}
vs := reflect.ValueOf(&s)
err := sliceScan(v.V().(types.Array), vs)
if err != nil {
return err
}
ref.Set(vs.Elem())
return nil
}
ref.Set(reflect.ValueOf(v.V()))
return nil
}
// test with supported stdlib types
switch ref.Type().String() {
case "time.Time":
if v.Type() == types.TextValue {
parsed, err := time.Parse(time.RFC3339Nano, v.V().(string))
if err != nil {
return err
}
ref.Set(reflect.ValueOf(parsed))
return nil
}
}
switch ref.Kind() {
case reflect.Struct:
v, err := CastAsDocument(v)
if err != nil {
return err
}
return structScan(v.V().(types.Document), ref)
case reflect.Slice:
if ref.Type().Elem().Kind() == reflect.Uint8 {
if v.Type() != types.TextValue && v.Type() != types.BlobValue {
return stringutil.Errorf("cannot scan value of type %s to byte slice", v.Type())
}
if v.Type() == types.TextValue {
ref.SetBytes([]byte(v.V().(string)))
} else {
ref.SetBytes(v.V().([]byte))
}
return nil
}
v, err := CastAsArray(v)
if err != nil {
return err
}
return sliceScan(v.V().(types.Array), ref.Addr())
case reflect.Array:
if ref.Type().Elem().Kind() == reflect.Uint8 {
if v.Type() != types.TextValue && v.Type() != types.BlobValue {
return stringutil.Errorf("cannot scan value of type %s to byte slice", v.Type())
}
reflect.Copy(ref, reflect.ValueOf(v.V()))
return nil
}
v, err := CastAsArray(v)
if err != nil {
return err
}
return sliceScan(v.V().(types.Array), ref.Addr())
case reflect.Map:
v, err := CastAsDocument(v)
if err != nil {
return err
}
return mapScan(v.V().(types.Document), ref)
}
return &ErrUnsupportedType{ref, "Invalid type"}
}
// ScanDocument scans a document into dest which must be either a struct pointer, a map or a map pointer.
func ScanDocument(d types.Document, t interface{}) error {
ref := reflect.ValueOf(t)
if !ref.IsValid() {
return errors.New("target must be pointer to a valid Go type")
}
switch reflect.Indirect(ref).Kind() {
case reflect.Map:
return mapScan(d, ref)
case reflect.Struct:
if ref.IsNil() {
ref.Set(reflect.New(ref.Type().Elem()))
}
return structScan(d, ref)
default:
return errors.New("target must be a either a pointer to struct, a map or a map pointer")
}
}
// ScanIterator scans a document iterator into a slice or fixed size array. t must be a pointer
// to a valid slice or array.
//
// It t is a slice pointer and its capacity is too low, a new slice will be allocated.
// Otherwise, its length is set to 0 so that its content is overwritten.
//
// If t is an array pointer, its capacity must be bigger than the length of a, otherwise an error is
// returned.
func ScanIterator(it Iterator, t interface{}) error {
a := iteratorArray{it: it}
return SliceScan(&a, t)
}
type iteratorArray struct {
it Iterator
}
func (it *iteratorArray) Iterate(fn func(i int, value types.Value) error) error {
count := 0
return it.it.Iterate(func(d types.Document) error {
err := fn(count, types.NewDocumentValue(d))
if err != nil {
return err
}
count++
return nil
})
}
func (it *iteratorArray) GetByIndex(i int) (types.Value, error) {
panic("not implemented")
}