forked from scylladb/gocqlx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
udt.go
74 lines (61 loc) · 1.72 KB
/
udt.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
// Copyright (C) 2017 ScyllaDB
// Use of this source code is governed by a ALv2-style
// license that can be found in the LICENSE file.
package gocqlx
import (
"fmt"
"reflect"
"github.com/gocql/gocql"
"github.com/scylladb/go-reflectx"
)
// UDT is a marker interface that needs to be embedded in a struct if you want
// to marshal or unmarshal it as a User Defined Type.
type UDT interface {
udt()
}
var (
_ gocql.UDTMarshaler = udt{}
_ gocql.UDTUnmarshaler = udt{}
)
type udt struct {
value reflect.Value
field map[string]reflect.Value
unsafe bool
}
func makeUDT(value reflect.Value, mapper *reflectx.Mapper, unsafe bool) udt {
return udt{
value: value,
field: mapper.FieldMap(value),
unsafe: unsafe,
}
}
func (u udt) MarshalUDT(name string, info gocql.TypeInfo) ([]byte, error) {
value, ok := u.field[name]
if !ok {
return nil, fmt.Errorf("missing name %q in %s", name, u.value.Type())
}
return gocql.Marshal(info, value.Interface())
}
func (u udt) UnmarshalUDT(name string, info gocql.TypeInfo, data []byte) error {
value, ok := u.field[name]
if !ok && !u.unsafe {
return fmt.Errorf("missing name %q in %s", name, u.value.Type())
}
return gocql.Unmarshal(info, data, value.Addr().Interface())
}
// udtWrapValue adds UDT wrapper if needed.
func udtWrapValue(value reflect.Value, mapper *reflectx.Mapper, unsafe bool) interface{} {
if value.Type().Implements(autoUDTInterface) {
return makeUDT(value, mapper, unsafe)
}
return value.Interface()
}
// udtWrapSlice adds UDT wrapper if needed.
func udtWrapSlice(mapper *reflectx.Mapper, unsafe bool, v []interface{}) []interface{} {
for i := range v {
if _, ok := v[i].(UDT); ok {
v[i] = makeUDT(reflect.ValueOf(v[i]), mapper, unsafe)
}
}
return v
}