gogo / protobuf

[Deprecated] Protocol Buffers for Go with Gadgets
Other
5.67k stars 807 forks source link

generate enum as string type instead of int #439

Open Tommy-42 opened 6 years ago

Tommy-42 commented 6 years ago

Hello, I am in a bit in a dead-end here. I have looked at the other issues about enum and string, but I think they didn;t match my case.

My case is : my db is POSTGRES and I use go-pg as orm.

my proto contain enum that are generated like this :

type Contact_Language int32

const (
    Contact_DUTCH   Contact_Language = 0
    Contact_ENGLISH Contact_Language = 1
    Contact_SPANISH Contact_Language = 2
    Contact_ITALIAN Contact_Language = 3
)

var Contact_Language_name = map[int32]string{
    0: "DUTCH",
    1: "ENGLISH",
    2: "SPANISH",
    3: "ITALIAN",
}
var Contact_Language_value = map[string]int32{
    "DUTCH":   0,
    "ENGLISH": 1,
    "SPANISH": 2,
    "ITALIAN": 3,
}

func (x Contact_Language) String() string {
    return proto.EnumName(Contact_Language_name, int32(x))
}
func (Contact_Language) EnumDescriptor() ([]byte, []int) { return fileDescriptorContact, []int{0, 2} }

the problem is : postgres store enum as a string/varchar

when I perform a select, the orm get the data then try to convert it to int32 ( since in with proto enum are init as int32 ).

Is there a way to generate enum as string type Contact_Language string instead of type Contact_Language int32 .

Does gogo/protobuf should have this option, or maybe you would have a solution for that ?

what do you think ?

awalterschulze commented 6 years ago

We provide customtype for bytes and messages, but not for int32s. Here people typically rely on casttype, but the type should be castable, which is not the case for string and int32. I don't think we provide such an option.

Does postgres maybe allow you to define a custom method that can cast your enum to a string and back? Just like you can define custom marshal and unmarshal methods for protobufs?

derekperkins commented 6 years ago

You should be able to just write your own Scanner/Valuer. I don't think this should be the job of this library. https://husobee.github.io/golang/database/2015/06/12/scanner-valuer.html https://www.reddit.com/r/golang/comments/710a1s/sql_valuerscanner_interface_issue/ https://gist.github.com/jmoiron/6979540