google-cloud-go icon indicating copy to clipboard operation
google-cloud-go copied to clipboard

feat(firestore): add support for omitzero struct tag

Open bhshkh opened this issue 7 months ago • 0 comments

Fixes: https://github.com/googleapis/google-cloud-go/issues/11885 This change introduces support for the omitzero struct tag option in the Firestore client library, similar to its behavior in encoding/json.

The omitzero tag allows struct fields to be omitted from Firestore documents during marshaling if their value is considered "zero". The determination of "zero" follows these rules:

  1. If the field's type has an IsZero() bool method, that method is called. If it returns true, the field is omitted.
  2. Otherwise, if the field's value is the Go default zero value for its type (e.g., 0 for numbers, false for bool, "" for strings, nil for pointers/interfaces/slices/maps, and the zero value for structs), it is omitted. This is checked using reflect.Value.IsZero().

If both omitzero and omitempty tags are present on a field, the field will be omitted if either condition (empty as per omitempty's rules, or zero as per omitzero's rules) is met.

This provides more fine-grained control over field serialization, especially for distinguishing between a field that is intentionally set to a zero value versus a field that is not set or should be considered absent.

Changes include:

  • Updated tagOptions and parseTag to recognize and process the omitzero option.
  • Modified structToProtoValue to implement the omission logic based on the omitzero tag.
  • Added comprehensive unit tests in to_value_test.go to verify the new functionality across various types, including those with IsZero() methods and combinations with omitempty.

Output:

bhshkh avatar May 21 '25 06:05 bhshkh