Skip to content
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.

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

Firestore: Add support for using snapshot cursors in collection group queries. #8810

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion firestore/google/cloud/firestore_v1/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,15 @@ def offset(self, num_to_skip):
all_descendants=self._all_descendants,
)

def _has_relation_with(self, snapshot):
"""
Check if given snapshot have relation with the
collection that this query applies to.
"""
is_same_collection = snapshot.reference._path[:-1] == self._parent._path
has_same_segment = snapshot.reference._path[-2] == self._parent._path[0]
return is_same_collection or (self._all_descendants and has_same_segment)

def _cursor_helper(self, document_fields, before, start):
"""Set values to be used for a ``start_at`` or ``end_at`` cursor.

Expand Down Expand Up @@ -419,7 +428,7 @@ def _cursor_helper(self, document_fields, before, start):
if isinstance(document_fields, tuple):
document_fields = list(document_fields)
elif isinstance(document_fields, document.DocumentSnapshot):
if document_fields.reference._path[:-1] != self._parent._path:
if not self._has_relation_with(document_fields):
raise ValueError(
"Cannot use snapshot from another collection as a cursor."
)
Expand Down
19 changes: 19 additions & 0 deletions firestore/tests/unit/v1/test_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,25 @@ def test_start_after(self):
self.assertIs(query._parent, collection)
self.assertEqual(query._start_at, (doc_fields, False))

def test_start_after_snapshot(self):
from google.cloud.firestore_v1.query import Query

client = _make_client()
parent_ref = self._make_one("parents", client=client).document("parent")

child_col = parent_ref.collection("children")
child_snapshot = child_col.document("child").get()

query = (
client.collection_group("children")
.where("d", "==", "Foo")
.start_after(child_snapshot)
)

self.assertIsInstance(query, Query)
self.assertEqual(query._parent._path, ("children",))
self.assertEqual(query._start_at, (child_snapshot, False))

def test_end_before(self):
from google.cloud.firestore_v1.query import Query

Expand Down