protobuf
protobuf copied to clipboard
Field descriptor isOptional returns true for non-optional marked field
What version of protobuf and what language are you using? 3.20.1 Java
What operating system (Linux, Windows, ...) and version? mac
What runtime / compiler are you using (e.g., python version or gcc version) java 18
What did you do?
message x {
fixed64 id = 5;
}
builder.build().getDescriptorForType().findFieldByName("id").isOptional()
What did you expect to see
false
What did you see instead?
true or otherwise there should be a different method to check for fieldPresence.
I realize this may be checking for the pb2 optional which in pb3 is by default true?
However how would then check for field presence in field descriptor?
I understand optional is implemented with oneof but there's no isOneOf either.
Use case
I'm trying to validate if field has been set, but I want to only validate against optional marked fields to avoid ambiguous checks.
Have you tried getting the value of https://github.com/protocolbuffers/protobuf/blob/db38a8c2dac34daa2d64bf904216997525617abf/src/google/protobuf/descriptor.proto#L242 ?
I also see this behavior: Protobuf version: 3.15.8 Language: C++ OS: Windows
Have you tried getting the value of https://github.com/protocolbuffers/protobuf/blob/db38a8c2dac34daa2d64bf904216997525617abf/src/google/protobuf/descriptor.proto#L242 ?
I didn't - think this could be a workaround or that this is the explicit way to correctly check for the new optional and the issue is invalid?
I found this: https://github.com/protocolbuffers/protobuf/blob/main/docs/implementing_proto3_presence.md
I suspect that this is "intended" and a result of the differences between language syntax proto2 and proto3. It seems like the implementation details of proto3 allow for more things to be optional even if they're not declared that way. In the doc above, in the API changes section, point 3, they suggest has_optional_keyword(). This works for my use case.
I think this issue could be closed with hasOptionalKeyword().
We triage inactive PRs and issues in order to make it easier to find active work. If this issue should remain active or becomes active again, please add a comment.
This issue is labeled inactive because the last activity was over 90 days ago.
We triage inactive PRs and issues in order to make it easier to find active work. If this issue should remain active or becomes active again, please reopen it.
This issue was closed and archived because there has been no new activity in the 14 days since the inactive label was added.
if considering a field could be wrapped in "oneof", a more comprehensive approach is to check:
field.containingOneof != null
proto3 optional field is producing synthetic oneof which is covered by the previous check