Replace Unsafe with Strict mechanism

Previously by default the presence of a missing field in
a udt would result in an error reported. The Unsafe
mechanism could be used to ignore these fields.

This PR changes the default behavior to ignoring missing
fields and only reporting an error if Strict mode is used.
This approach is in line with the gocql.
This commit is contained in:
sylwiaszunejko
2024-06-25 13:34:50 +02:00
committed by Sylwia Szunejko
parent 6a60650668
commit 7072863b0c
6 changed files with 69 additions and 70 deletions

18
udt.go
View File

@@ -26,14 +26,14 @@ var (
type udt struct {
field map[string]reflect.Value
value reflect.Value
unsafe bool
strict bool
}
func makeUDT(value reflect.Value, mapper *reflectx.Mapper, unsafe bool) udt {
func makeUDT(value reflect.Value, mapper *reflectx.Mapper, strict bool) udt {
return udt{
value: value,
field: mapper.FieldMap(value),
unsafe: unsafe,
strict: strict,
}
}
@@ -42,7 +42,7 @@ func (u udt) MarshalUDT(name string, info gocql.TypeInfo) ([]byte, error) {
if ok {
return gocql.Marshal(info, value.Interface())
}
if u.unsafe {
if !u.strict {
return nil, nil
}
return nil, fmt.Errorf("missing name %q in %s", name, u.value.Type())
@@ -53,25 +53,25 @@ func (u udt) UnmarshalUDT(name string, info gocql.TypeInfo, data []byte) error {
if ok {
return gocql.Unmarshal(info, data, value.Addr().Interface())
}
if u.unsafe {
if !u.strict {
return nil
}
return fmt.Errorf("missing name %q in %s", name, u.value.Type())
}
// udtWrapValue adds UDT wrapper if needed.
func udtWrapValue(value reflect.Value, mapper *reflectx.Mapper, unsafe bool) interface{} {
func udtWrapValue(value reflect.Value, mapper *reflectx.Mapper, strict bool) interface{} {
if value.Type().Implements(autoUDTInterface) {
return makeUDT(value, mapper, unsafe)
return makeUDT(value, mapper, strict)
}
return value.Interface()
}
// udtWrapSlice adds UDT wrapper if needed.
func udtWrapSlice(mapper *reflectx.Mapper, unsafe bool, v []interface{}) []interface{} {
func udtWrapSlice(mapper *reflectx.Mapper, strict bool, v []interface{}) []interface{} {
for i := range v {
if _, ok := v[i].(UDT); ok {
v[i] = makeUDT(reflect.ValueOf(v[i]), mapper, unsafe)
v[i] = makeUDT(reflect.ValueOf(v[i]), mapper, strict)
}
}
return v