GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(firestore): add BSON read deserialization support by ohmayr · Pull Request #18402 · googleapis/google-cloud-python

feat(firestore): add BSON read deserialization support #18402

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
ohmayr merged 9 commits into main from bson-pr2-reads
Sep 25, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

feat(firestore): add BSON read deserialization support #18402

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
9 commits
Select commit Hold shift + click to select a range
21754b7
feat(firestore): add BSON read deserialization support
ohmayr Sep 16, 2026
eee4580
refactor(firestore): address review feedback for BSON read deserializ…
ohmayr Sep 21, 2026
8db5c0d
refactor(firestore): restore precise return types and docstrings on d…
ohmayr Sep 21, 2026
b9367d6
refactor(firestore): align decode_dict and PipelineResult.data return…
ohmayr Sep 21, 2026
2d3272a
fix(firestore): restore required client parameter and format comprehe…
ohmayr Sep 22, 2026
09de539
refactor(firestore): expose BSONType publicly
ohmayr Sep 23, 2026
28ad79e
refactor(firestore): refine BSON read deserialization typing and fall…
ohmayr Sep 24, 2026
384d5c0
fix(firestore): use repr formatting for data in PipelineResult.__repr__
ohmayr Sep 24, 2026
de2670c
test(firestore): assert BSONDecimal128 in special values system tests
ohmayr Sep 24, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

4 changes: 4 additions & 0 deletions 4 .librarian/generator-input/client-post-processing/firestore-integration.yaml
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ replacements:
BSONObjectId,
BSONRegex,
BSONTimestamp,
BSONType,
)
from google.cloud.firestore_v1.client import Client
from google.cloud.firestore_v1.collection import CollectionReference
Expand Down Expand Up @@ -188,6 +189,7 @@ replacements:
"BSONObjectId",
"BSONRegex",
"BSONTimestamp",
"BSONType",
"Client",
"CountAggregation",
"CollectionGroup",
Expand Down Expand Up @@ -268,6 +270,7 @@ replacements:
BSONObjectId,
BSONRegex,
BSONTimestamp,
BSONType,
Client,
CollectionGroup,
CollectionReference,
Expand Down Expand Up @@ -333,6 +336,7 @@ replacements:
"BSONObjectId",
"BSONRegex",
"BSONTimestamp",
"BSONType",
"Client",
"CountAggregation",
"CollectionGroup",
Expand Down
2 changes: 2 additions & 0 deletions 2 packages/google-cloud-firestore/google/cloud/firestore/__init__.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
BSONObjectId,
BSONRegex,
BSONTimestamp,
BSONType,
Client,
CollectionGroup,
CollectionReference,
Expand Down Expand Up @@ -108,6 +109,7 @@
"BSONObjectId",
"BSONRegex",
"BSONTimestamp",
"BSONType",
"Client",
"CountAggregation",
"CollectionGroup",
Expand Down
2 changes: 2 additions & 0 deletions 2 packages/google-cloud-firestore/google/cloud/firestore_v1/__init__.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
BSONObjectId,
BSONRegex,
BSONTimestamp,
BSONType,
)
from google.cloud.firestore_v1.client import Client
from google.cloud.firestore_v1.collection import CollectionReference
Expand Down Expand Up @@ -165,6 +166,7 @@
"BSONObjectId",
"BSONRegex",
"BSONTimestamp",
"BSONType",
"Client",
"CountAggregation",
"CollectionGroup",
Expand Down
36 changes: 28 additions & 8 deletions 36 packages/google-cloud-firestore/google/cloud/firestore_v1/_helpers.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
import google
from google.cloud import exceptions # type: ignore
from google.cloud.firestore_v1 import transforms, types
from google.cloud.firestore_v1.bson import _BSONType
from google.cloud.firestore_v1.bson import BSONType
from google.cloud.firestore_v1.field_path import FieldPath, parse_field_path
from google.cloud.firestore_v1.types import common, document, write
from google.cloud.firestore_v1.types.write import DocumentTransform
Expand Down Expand Up @@ -211,7 +211,7 @@ def encode_value(value) -> types.document.Value:
if document_path is not None:
return document.Value(reference_value=document_path)

if isinstance(value, _BSONType):
if isinstance(value, BSONType):
return encode_value(value._to_map_value())

if isinstance(value, GeoPoint):
Expand Down Expand Up @@ -350,7 +350,18 @@ def reference_value_to_document(reference_value, client) -> Any:
def decode_value(
value, client
) -> Union[
None, bool, int, float, list, datetime.datetime, str, bytes, dict, GeoPoint, Vector
None,
bool,
int,
float,
list,
datetime.datetime,
str,
bytes,
dict,
GeoPoint,
Vector,
BSONType,
]:
"""Converts a Firestore protobuf ``Value`` to a native Python value.

Expand All @@ -362,7 +373,9 @@ def decode_value(

Returns:
Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]: A native
str, bytes, dict, ~google.cloud.Firestore.GeoPoint, \
~google.cloud.firestore_v1.vector.Vector, \
~google.cloud.firestore_v1.bson.BSONType]: A native \
Python value converted from the ``value``.

Raises:
Expand Down Expand Up @@ -402,7 +415,10 @@ def decode_value(
raise ValueError("Unknown ``value_type``", value_type)


def decode_dict(value_fields, client) -> Union[dict, Vector]:
def decode_dict(
value_fields,
client,
) -> Union[dict, Vector, BSONType, bytes]:
"""Converts a protobuf map of Firestore ``Value``-s.

Args:
Expand All @@ -412,9 +428,9 @@ def decode_dict(value_fields, client) -> Union[dict, Vector]:
A client that has a document factory.

Returns:
Dict[str, Union[NoneType, bool, int, float, datetime.datetime, \
str, bytes, dict, ~google.cloud.Firestore.GeoPoint]]: A dictionary
of native Python values converted from the ``value_fields``.
Union[dict, ~google.cloud.firestore_v1.vector.Vector, \
~google.cloud.firestore_v1.bson.BSONType, bytes]: A dictionary of native \
Python values, Vector, BSON object, or bytes converted from ``value_fields``.
"""
value_fields_pb = getattr(value_fields, "_pb", value_fields)
res = {key: decode_value(value, client) for key, value in value_fields_pb.items()}
Expand All @@ -425,6 +441,10 @@ def decode_dict(value_fields, client) -> Union[dict, Vector]:
values = cast(Sequence[float], res["value"])
return Vector(values)

decoded = BSONType._from_dict(res)
if decoded is not None:
return decoded

return res


Expand Down
61 changes: 51 additions & 10 deletions 61 packages/google-cloud-firestore/google/cloud/firestore_v1/bson.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@
import abc
import decimal
import re
from typing import Any, Dict, Union
from typing import Any, Callable, Dict, Optional, Union

__all__ = [
"BSONType",
"BSONObjectId",
"BSONMinKey",
"BSONMaxKey",
Expand All @@ -44,7 +45,7 @@
_HEX_24_REGEX = re.compile(r"^[0-9a-fA-F]{24}$")


class _BSONType(abc.ABC):
class BSONType(abc.ABC):
"""Abstract base class for all BSON type containers in Firestore."""

__slots__ = ()
Expand All @@ -65,11 +66,33 @@ def __eq__(self, other: Any) -> bool:
def __hash__(self) -> int:
"""Hash representation contract for set and dictionary keys."""

@classmethod
def _from_dict(cls, data: Any) -> Optional[Union["BSONType", bytes]]:
"""Deserializes a BSON wire map dictionary into a BSON instance or bytes.

Args:
data (Any): Potential BSON wire map dictionary.
Comment thread
daniel-sanche marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.


Returns:
Optional[Union[BSONType, bytes]]: Deserialized BSON container
instance or bytes, or None if not a BSON wire map or if decoding fails.
"""
if not isinstance(data, dict) or len(data) != 1:
return None
key, val = next(iter(data.items()))
decoder = _BSON_DECODERS.get(key)
if decoder is None:
return None
try:
return decoder(val)
except Exception:
return None

def __repr__(self) -> str:
return f"{self.__class__.__name__}()"


class BSONObjectId(_BSONType):
class BSONObjectId(BSONType):
"""Represents a 12-byte BSON ObjectId identifier.

Args:
Expand Down Expand Up @@ -128,7 +151,7 @@ def __hash__(self) -> int:
return hash((type(self), self._value))


class BSONMinKey(_BSONType):
class BSONMinKey(BSONType):
"""Represents the BSON MinKey sentinel value for query range boundaries."""

__slots__ = ()
Expand All @@ -146,7 +169,7 @@ def __hash__(self) -> int:
return hash(type(self))


class BSONMaxKey(_BSONType):
class BSONMaxKey(BSONType):
"""Represents the BSON MaxKey sentinel value for query range boundaries."""

__slots__ = ()
Expand All @@ -164,7 +187,7 @@ def __hash__(self) -> int:
return hash(type(self))


class BSONInt32(_BSONType):
class BSONInt32(BSONType):
"""Represents a 32-bit signed integer value container for Firestore BSON.

Args:
Expand Down Expand Up @@ -221,7 +244,7 @@ def __hash__(self) -> int:
return hash((type(self), self._value))


class BSONBinary(_BSONType):
class BSONBinary(BSONType):
"""Represents a BSON binary data container with a subtype for Firestore.

Args:
Expand Down Expand Up @@ -286,7 +309,7 @@ def __hash__(self) -> int:
return hash((type(self), self._data, self._subtype))


class BSONTimestamp(_BSONType):
class BSONTimestamp(BSONType):
"""Container for BSON Timestamp values.

Args:
Expand Down Expand Up @@ -347,7 +370,7 @@ def __hash__(self) -> int:
return hash((type(self), self._seconds, self._increment))


class BSONRegex(_BSONType):
class BSONRegex(BSONType):
"""Represents a BSON Regular Expression container for Firestore.

Args:
Expand Down Expand Up @@ -409,7 +432,7 @@ def __hash__(self) -> int:
return hash((type(self), self._pattern, self._options))


class BSONDecimal128(_BSONType):
class BSONDecimal128(BSONType):
"""Represents a BSON 128-bit Decimal container for Firestore.

Args:
Expand Down Expand Up @@ -507,3 +530,21 @@ def __hash__(self) -> int:
return hash(d)
except decimal.InvalidOperation:
return hash((type(self), self._value))


_BSON_DECODERS: Dict[str, Callable[..., Optional[Union[BSONType, bytes]]]] = {
"__oid__": BSONObjectId,
"__min__": lambda _: BSONMinKey(),
"__max__": lambda _: BSONMaxKey(),
"__int__": BSONInt32,
"__decimal128__": BSONDecimal128,
"__binary__": lambda v: (v[1:] if v[0] == 0 else BSONBinary(v[1:], subtype=v[0]))
if isinstance(v, (bytes, bytearray)) and len(v) >= 1
else None,
"__request_timestamp__": lambda v: BSONTimestamp(v["seconds"], v["increment"])
if isinstance(v, dict) and "seconds" in v and "increment" in v
else None,
"__regex__": lambda v: BSONRegex(v["pattern"], v.get("options", ""))
if isinstance(v, dict) and "pattern" in v
else None,
}
Comment thread
daniel-sanche marked this conversation as resolved.
Resolved

Uh oh!

There was an error while loading. Please reload this page.

5 changes: 3 additions & 2 deletions 5 packages/google-cloud-firestore/google/cloud/firestore_v1/pipeline_result.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
from google.cloud.firestore_v1.async_transaction import AsyncTransaction
from google.cloud.firestore_v1.base_client import BaseClient
from google.cloud.firestore_v1.base_document import BaseDocumentReference
from google.cloud.firestore_v1.bson import BSONType
from google.cloud.firestore_v1.client import Client
from google.cloud.firestore_v1.pipeline import Pipeline
from google.cloud.firestore_v1.pipeline_expressions import Constant
Expand Down Expand Up @@ -90,7 +91,7 @@ def __init__(
self._update_time = update_time

def __repr__(self):
return f"{type(self).__name__}(data={self.data()})"
return f"{type(self).__name__}(data={self.data()!r})"

@property
def ref(self) -> BaseDocumentReference | None:
Expand Down Expand Up @@ -138,7 +139,7 @@ def __eq__(self, other: object) -> bool:
return NotImplemented
return (self._ref == other._ref) and (self._fields_pb == other._fields_pb)

def data(self) -> dict | "Vector" | None:
def data(self) -> dict | "Vector" | "BSONType" | bytes | None:
"""
Retrieves all fields in the result.

Expand Down
34 changes: 8 additions & 26 deletions 34 packages/google-cloud-firestore/tests/system/test_system.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -1285,9 +1285,9 @@ def test_unicode_doc(client, cleanup, database):


@pytest.mark.parametrize("database", [FIRESTORE_ENTERPRISE_DB], indirect=True)
def test_bson_document_writes(client, cleanup, database):
"""Test write operations for BSON types on Enterprise DB."""
collection_id = "bson_type_writes_" + UNIQUE_RESOURCE_ID
def test_bson_document_read_and_write(client, cleanup, database):
"""Test read and write operations for BSON types on Enterprise DB."""
collection_id = "bson_type_read_write_" + UNIQUE_RESOURCE_ID
doc_ref = client.collection(collection_id).document("bson_doc")
cleanup(doc_ref.delete)

Expand All @@ -1296,6 +1296,7 @@ def test_bson_document_writes(client, cleanup, database):
"min_key": BSONMinKey(),
"max_key": BSONMaxKey(),
"int32_val": BSONInt32(42),
"binary_val_sub0": b"hello",
"binary_val_sub128": BSONBinary(b"world", subtype=128),
"timestamp_val": BSONTimestamp(1700000000, 1),
"regex_val": BSONRegex("^hello.*$", options="i"),
Expand All @@ -1306,26 +1307,7 @@ def test_bson_document_writes(client, cleanup, database):

snapshot = doc_ref.get()
assert snapshot.exists
assert snapshot.to_dict() == {
"user_id": {"__oid__": "507f191e810c19729de860ea"},
"min_key": {"__min__": None},
"max_key": {"__max__": None},
"int32_val": {"__int__": 42},
"binary_val_sub128": {"__binary__": b"\x80world"},
"timestamp_val": {
"__request_timestamp__": {
"seconds": 1700000000,
"increment": 1,
}
},
"regex_val": {
"__regex__": {
"pattern": "^hello.*$",
"options": "i",
}
},
"decimal128_val": {"__decimal128__": "123.45"},
}
assert snapshot.to_dict() == bson_payload


@pytest.mark.parametrize("database", [FIRESTORE_ENTERPRISE_DB], indirect=True)
Expand Down Expand Up @@ -1362,9 +1344,9 @@ def test_bson_decimal128_special_values(client, cleanup, database):
snapshot = doc_ref.get()
assert snapshot.exists
assert snapshot.to_dict() == {
"inf_val": {"__decimal128__": "Infinity"},
"neg_inf_val": {"__decimal128__": "-Infinity"},
"nan_val": {"__decimal128__": "NaN"},
"inf_val": BSONDecimal128("Infinity"),
"neg_inf_val": BSONDecimal128("-Infinity"),
"nan_val": BSONDecimal128("NaN"),
}


Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.