Optional Fields

A common issue with Protobufs is that the way that nil values are represented: a zero-valued primitive field isn’t encoded into the binary representation, this means that applications cannot distinguish between zero and not-set for primitive fields.

To support this, the Protobuf project supports some Well-Known types called “wrapper types”. For example, the wrapper type for a bool, is called google.protobuf.BoolValue and is defined as:

ent/proto/entpb/entpb.proto

  1. // Wrapper message for `bool`.
  2. //
  3. // The JSON representation for `BoolValue` is JSON `true` and `false`.
  4. message BoolValue {
  5. // The bool value.
  6. bool value = 1;
  7. }

When entproto generates a Protobuf message definition, it uses these wrapper types to represent “Optional” ent fields.

Let’s see this in action, modifying our ent schema to include an optional field:

ent/schema/user.go

  1. // Fields of the User.
  2. func (User) Fields() []ent.Field {
  3. return []ent.Field{
  4. field.String("name").
  5. Unique().
  6. Annotations(
  7. entproto.Field(2),
  8. ),
  9. field.String("email_address").
  10. Unique().
  11. Annotations(
  12. entproto.Field(3),
  13. ),
  14. field.String("alias").
  15. Optional().
  16. Annotations(entproto.Field(4)),
  17. }
  18. }

Re-running go generate ./..., observe that our Protobuf definition for User now looks like:

ent/proto/entpb/entpb.proto

  1. message User {
  2. int32 id = 1;
  3. string name = 2;
  4. string email_address = 3;
  5. google.protobuf.StringValue alias = 4; // <-- this is new
  6. repeated Category administered = 5;
  7. }

The generated service implementation also utilize this field. Observe in entpb_user_service.go:

ent/proto/entpb/entpb_user_service.go

  1. func (svc *UserService) createBuilder(user *User) (*ent.UserCreate, error) {
  2. m := svc.client.User.Create()
  3. if user.GetAlias() != nil {
  4. userAlias := user.GetAlias().GetValue()
  5. m.SetAlias(userAlias)
  6. }
  7. userEmailAddress := user.GetEmailAddress()
  8. m.SetEmailAddress(userEmailAddress)
  9. userName := user.GetName()
  10. m.SetName(userName)
  11. for _, item := range user.GetAdministered() {
  12. administered := int(item.GetId())
  13. m.AddAdministeredIDs(administered)
  14. }
  15. return m, nil
  16. }

To use the wrapper types in our client code, we can use helper methods supplied by the wrapperspb package to easily build instances of these types. For example in cmd/client/main.go:

  1. func randomUser() *entpb.User {
  2. return &entpb.User{
  3. Name: fmt.Sprintf("user_%d", rand.Int()),
  4. EmailAddress: fmt.Sprintf("user_%d@example.com", rand.Int()),
  5. Alias: wrapperspb.String("John Doe"),
  6. }
  7. }