Skip to content

Commit 32190fe

Browse files
GODRIVER-3470 UnmarshalerDecodeValue to mirror ValueUnmarshalerDecodeValue null check
1 parent 7d2be3c commit 32190fe

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

bson/bsoncodec/default_value_decoders.go

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1569,6 +1569,18 @@ func (dvd DefaultValueDecoders) UnmarshalerDecodeValue(_ DecodeContext, vr bsonr
15691569
return ValueDecoderError{Name: "UnmarshalerDecodeValue", Types: []reflect.Type{tUnmarshaler}, Received: val}
15701570
}
15711571

1572+
// If BSON value is null and the go value is a pointer, then don't call
1573+
// UnmarshalBSONValue. Even if the Go pointer is already initialized (i.e.,
1574+
// non-nil), encountering null in BSON will result in the pointer being
1575+
// directly set to nil here. Since the pointer is being replaced with nil,
1576+
// there is no opportunity (or reason) for the custom UnmarshalBSONValue logic
1577+
// to be called.
1578+
if val.Kind() == reflect.Ptr && vr.Type() == bsontype.Null {
1579+
val.Set(reflect.Zero(val.Type()))
1580+
1581+
return vr.ReadNull()
1582+
}
1583+
15721584
if val.Kind() == reflect.Ptr && val.IsNil() {
15731585
if !val.CanSet() {
15741586
return ValueDecoderError{Name: "UnmarshalerDecodeValue", Types: []reflect.Type{tUnmarshaler}, Received: val}
@@ -1581,18 +1593,6 @@ func (dvd DefaultValueDecoders) UnmarshalerDecodeValue(_ DecodeContext, vr bsonr
15811593
return err
15821594
}
15831595

1584-
// If the target Go value is a pointer and the BSON field value is empty, set the value to the
1585-
// zero value of the pointer (nil) and don't call UnmarshalBSON. UnmarshalBSON has no way to
1586-
// change the pointer value from within the function (only the value at the pointer address),
1587-
// so it can't set the pointer to "nil" itself. Since the most common Go value for an empty BSON
1588-
// field value is "nil", we set "nil" here and don't call UnmarshalBSON. This behavior matches
1589-
// the behavior of the Go "encoding/json" unmarshaler when the target Go value is a pointer and
1590-
// the JSON field value is "null".
1591-
if val.Kind() == reflect.Ptr && len(src) == 0 {
1592-
val.Set(reflect.Zero(val.Type()))
1593-
return nil
1594-
}
1595-
15961596
if !val.Type().Implements(tUnmarshaler) {
15971597
if !val.CanAddr() {
15981598
return ValueDecoderError{Name: "UnmarshalerDecodeValue", Types: []reflect.Type{tUnmarshaler}, Received: val}

0 commit comments

Comments
 (0)