[GODRIVER-452] bson package unable to Decode Enum values Created: 07/Jun/18  Updated: 28/Oct/23  Resolved: 10/Sep/18

Status: Closed
Project: Go Driver
Component/s: BSON
Affects Version/s: 0.0.6
Fix Version/s: 0.0.14

Type: Bug Priority: Major - P3
Reporter: Sercan Degirmenci Assignee: Kristofer Brandow (Inactive)
Resolution: Fixed Votes: 1
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Attachments: File test_enum.go    

 Description   

I am trying to use new go driver but I found with regarding BSON decoding. I can reproduce the issue with the file in the attachment. The problem is with the defined types. Following EnumType has no problem with encoding but can't decode the original value.
 
type EnumType int32
const EnumType_A EnumType = 1
type Dummy struct

{ Tt EnumType `bson:"tt"` }

 Comments   
Comment by Kristofer Brandow (Inactive) [ 10/Sep/18 ]

Hi dgregoire,

Now that GODRIVER-494 has been merged you can use the new bson.Decoderv2 to handle this specific case.

Thanks,

Kris

Comment by Dominic Gregoire [ 31/Aug/18 ]

As a workaround - it's a bit of a kludge, but worth it for larger structs - you can

test.go

type Value int
type Test struct {
    Val Value
    OtherVal int
} 
 
func (u * Test) UnmarshalBSON(data []byte) error {
	type Alias Test
 
	aux := &struct {
		Val int `bson:"val"`
		*Alias
	}{
		Alias: (*Alias)(u),
	}
 
	if err := bson.Unmarshal(data, aux); err != nil {
		return err
	}
 
	// val
	u.Val = Value(aux.Val)
 
	return nil
}

Comment by Kristofer Brandow (Inactive) [ 01/Aug/18 ]

Hi tonymims,

We're working on new implementations for Encoder and Decoder. These will allow users to register custom handlers for the encoding and decoding process of specific types. The new encoders and decoders will also be able to handle the base types as defined by reflect.Kind. This should solve the problems in this ticket. You can follow the progress of the new implementation by watching GODRIVER-494.

Thanks,

Kris

Comment by tony [ 01/Aug/18 ]

I have the same problem with a user-defined type pointing to an int as defined below:

type Value int
type Test struct {
    Val Value `bson:"val"`
} 

Marshaling goes well, but Unmarshaling always sets the Val field to zero as the type of my field is not found in the switch/case statement decoding an int, in function getReflectValue from file bson/decode.go.

For my case it could be fixed easily by adding a default at the end of the switch on containerType, and trying to convert the value to the real container type:

case 0x12:
    i := v.Int64()
    switch containerType {
    ...
    default:
        val = reflect.ValueOf(i).Convert(containerType)
    }

But I guess you would need to do that on a bunch of other place in the code.

Generated at Thu Feb 08 08:34:15 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.