feat(firestore): add BSONInt32 support - #18388
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces the BSONInt32 class to represent 32-bit signed integers in Firestore BSON, updating the package exports and adding system and unit tests. The feedback suggests improving the __hash__ method of BSONInt32 to include the class type in the hash tuple, which prevents hash collisions with plain integers since they are not considered equal.
| def __hash__(self) -> int: | ||
| return hash(self._value) |
There was a problem hiding this comment.
The current implementation of __hash__ returns hash(self._value). Since BSONInt32(42) != 42 (as verified in the unit tests), having the same hash value for both BSONInt32(42) and 42 violates the best practice of minimizing hash collisions for unequal objects of different types. If both are stored in the same dictionary or set, it will cause a hash collision and degrade lookup performance.
Consider incorporating the class type into the hash to ensure distinct hash values for BSONInt32 instances compared to plain integers.
| def __hash__(self) -> int: | |
| return hash(self._value) | |
| def __hash__(self) -> int: | |
| return hash((BSONInt32, self._value)) |
f05ed9e to
789ea14
Compare
74a4eb4 to
0f09d53
Compare
0f09d53 to
ac6b148
Compare
ac6b148 to
b73122c
Compare
b73122c to
49a7be6
Compare
| if not (self._MIN_INT32 <= value <= self._MAX_INT32): | ||
| raise ValueError( | ||
| f"BSONInt32 value must be between {self._MIN_INT32} and {self._MAX_INT32}." | ||
| ) |
There was a problem hiding this comment.
nit: we can probably rely on the backend for this kind of validation. But this is fine too
This PR adds support for BSONInt32 in the Firestore Python SDK.
BSONInt32allows developers to explicitly store 32-bit signed integer values in Firestore documents according to the official Firestore BSON specification.Added$-2,147,483,648$ and $2,147,483,647$ .
BSONInt32class: Introduces a container class that holds 32-bit signed integers betweenInput Validation: Automatically rejects booleans and non-integer types with a TypeError, and raises a
ValueErrorif a number is outside 32-bit signed integer bounds.Wire Format: Serializes to
{"__int__": value}for Firestore BSON document writes.Package Exports: Exported
BSONInt32ingoogle.cloud.firestoreandgoogle.cloud.firestore_v1, and updated post-processing generator rules to preserve exports during regeneration.Testing: Added unit tests covering validation, equality, hashing, copying, and pickling, plus verified sync and async document writes on Firestore Enterprise DB.
Fixes b/562163919 🦕