Skip to content

Commit 55da695

Browse files
authored
feat: integrate limit to last (#145)
* feat: integrate limit_to_last changes from #57 to async * fix: whitespace in docs * fix: whitespace in docs
1 parent eb19712 commit 55da695

File tree

11 files changed

+410
-134
lines changed

11 files changed

+410
-134
lines changed

google/cloud/firestore_v1/async_collection.py

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,6 @@
1313
# limitations under the License.
1414

1515
"""Classes for representing collections for the Google Cloud Firestore API."""
16-
import warnings
17-
18-
1916
from google.cloud.firestore_v1.base_collection import (
2017
BaseCollectionReference,
2118
_auto_id,
@@ -130,17 +127,26 @@ async def list_documents(
130127
async for i in iterator:
131128
yield _item_to_document_ref(self, i)
132129

133-
async def get(
134-
self, transaction=None
135-
) -> AsyncGenerator[async_document.DocumentSnapshot, Any]:
136-
"""Deprecated alias for :meth:`stream`."""
137-
warnings.warn(
138-
"'Collection.get' is deprecated: please use 'Collection.stream' instead.",
139-
DeprecationWarning,
140-
stacklevel=2,
141-
)
142-
async for d in self.stream(transaction=transaction):
143-
yield d # pytype: disable=name-error
130+
async def get(self, transaction=None) -> list:
131+
"""Read the documents in this collection.
132+
133+
This sends a ``RunQuery`` RPC and returns a list of documents
134+
returned in the stream of ``RunQueryResponse`` messages.
135+
136+
Args:
137+
transaction
138+
(Optional[:class:`~google.cloud.firestore_v1.transaction.Transaction`]):
139+
An existing transaction that this query will run in.
140+
141+
If a ``transaction`` is used and it already has write operations
142+
added, this method cannot be used (i.e. read-after-write is not
143+
allowed).
144+
145+
Returns:
146+
list: The documents in this collection that match the query.
147+
"""
148+
query = self._query()
149+
return await query.get(transaction=transaction)
144150

145151
async def stream(
146152
self, transaction=None

google/cloud/firestore_v1/async_query.py

Lines changed: 47 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,11 @@
1818
a :class:`~google.cloud.firestore_v1.collection.Collection` and that can be
1919
a more common way to create a query than direct usage of the constructor.
2020
"""
21-
import warnings
22-
2321
from google.cloud.firestore_v1.base_query import (
2422
BaseQuery,
2523
_query_response_to_snapshot,
2624
_collection_group_query_response_to_snapshot,
25+
_enum_from_direction,
2726
)
2827

2928
from google.cloud.firestore_v1 import _helpers
@@ -94,6 +93,7 @@ def __init__(
9493
field_filters=(),
9594
orders=(),
9695
limit=None,
96+
limit_to_last=False,
9797
offset=None,
9898
start_at=None,
9999
end_at=None,
@@ -105,23 +105,51 @@ def __init__(
105105
field_filters=field_filters,
106106
orders=orders,
107107
limit=limit,
108+
limit_to_last=limit_to_last,
108109
offset=offset,
109110
start_at=start_at,
110111
end_at=end_at,
111112
all_descendants=all_descendants,
112113
)
113114

114-
async def get(
115-
self, transaction=None
116-
) -> AsyncGenerator[async_document.DocumentSnapshot, None]:
117-
"""Deprecated alias for :meth:`stream`."""
118-
warnings.warn(
119-
"'AsyncQuery.get' is deprecated: please use 'AsyncQuery.stream' instead.",
120-
DeprecationWarning,
121-
stacklevel=2,
122-
)
123-
async for d in self.stream(transaction=transaction):
124-
yield d
115+
async def get(self, transaction=None) -> list:
116+
"""Read the documents in the collection that match this query.
117+
118+
This sends a ``RunQuery`` RPC and returns a list of documents
119+
returned in the stream of ``RunQueryResponse`` messages.
120+
121+
Args:
122+
transaction
123+
(Optional[:class:`~google.cloud.firestore_v1.transaction.Transaction`]):
124+
An existing transaction that this query will run in.
125+
126+
If a ``transaction`` is used and it already has write operations
127+
added, this method cannot be used (i.e. read-after-write is not
128+
allowed).
129+
130+
Returns:
131+
list: The documents in the collection that match this query.
132+
"""
133+
is_limited_to_last = self._limit_to_last
134+
135+
if self._limit_to_last:
136+
# In order to fetch up to `self._limit` results from the end of the
137+
# query flip the defined ordering on the query to start from the
138+
# end, retrieving up to `self._limit` results from the backend.
139+
for order in self._orders:
140+
order.direction = _enum_from_direction(
141+
self.DESCENDING
142+
if order.direction == self.ASCENDING
143+
else self.ASCENDING
144+
)
145+
self._limit_to_last = False
146+
147+
result = self.stream(transaction=transaction)
148+
result = [d async for d in result]
149+
if is_limited_to_last:
150+
result = list(reversed(result))
151+
152+
return result
125153

126154
async def stream(
127155
self, transaction=None
@@ -152,6 +180,12 @@ async def stream(
152180
:class:`~google.cloud.firestore_v1.async_document.DocumentSnapshot`:
153181
The next document that fulfills the query.
154182
"""
183+
if self._limit_to_last:
184+
raise ValueError(
185+
"Query results for queries that include limit_to_last() "
186+
"constraints cannot be streamed. Use Query.get() instead."
187+
)
188+
155189
parent_path, expected_prefix = self._parent._parent_info()
156190
response_iterator = await self._client._firestore_api.run_query(
157191
request={

google/cloud/firestore_v1/base_collection.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,10 @@ def order_by(self, field_path, **kwargs) -> NoReturn:
205205
def limit(self, count) -> NoReturn:
206206
"""Create a limited query with this collection as parent.
207207
208+
.. note::
209+
`limit` and `limit_to_last` are mutually exclusive.
210+
Setting `limit` will drop previously set `limit_to_last`.
211+
208212
See
209213
:meth:`~google.cloud.firestore_v1.query.Query.limit` for
210214
more information on this method.
@@ -220,6 +224,24 @@ def limit(self, count) -> NoReturn:
220224
query = self._query()
221225
return query.limit(count)
222226

227+
def limit_to_last(self, count):
228+
"""Create a limited to last query with this collection as parent.
229+
.. note::
230+
`limit` and `limit_to_last` are mutually exclusive.
231+
Setting `limit_to_last` will drop previously set `limit`.
232+
See
233+
:meth:`~google.cloud.firestore_v1.query.Query.limit_to_last`
234+
for more information on this method.
235+
Args:
236+
count (int): Maximum number of documents to return that
237+
match the query.
238+
Returns:
239+
:class:`~google.cloud.firestore_v1.query.Query`:
240+
A limited to last query.
241+
"""
242+
query = self._query()
243+
return query.limit_to_last(count)
244+
223245
def offset(self, num_to_skip) -> NoReturn:
224246
"""Skip to an offset in a query with this collection as parent.
225247

google/cloud/firestore_v1/base_query.py

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,8 @@ class BaseQuery(object):
9898
The "order by" entries to use in the query.
9999
limit (Optional[int]):
100100
The maximum number of documents the query is allowed to return.
101+
limit_to_last (Optional[bool]):
102+
Denotes whether a provided limit is applied to the end of the result set.
101103
offset (Optional[int]):
102104
The number of results to skip.
103105
start_at (Optional[Tuple[dict, bool]]):
@@ -146,6 +148,7 @@ def __init__(
146148
field_filters=(),
147149
orders=(),
148150
limit=None,
151+
limit_to_last=False,
149152
offset=None,
150153
start_at=None,
151154
end_at=None,
@@ -156,6 +159,7 @@ def __init__(
156159
self._field_filters = field_filters
157160
self._orders = orders
158161
self._limit = limit
162+
self._limit_to_last = limit_to_last
159163
self._offset = offset
160164
self._start_at = start_at
161165
self._end_at = end_at
@@ -170,6 +174,7 @@ def __eq__(self, other):
170174
and self._field_filters == other._field_filters
171175
and self._orders == other._orders
172176
and self._limit == other._limit
177+
and self._limit_to_last == other._limit_to_last
173178
and self._offset == other._offset
174179
and self._start_at == other._start_at
175180
and self._end_at == other._end_at
@@ -224,6 +229,7 @@ def select(self, field_paths) -> "BaseQuery":
224229
field_filters=self._field_filters,
225230
orders=self._orders,
226231
limit=self._limit,
232+
limit_to_last=self._limit_to_last,
227233
offset=self._offset,
228234
start_at=self._start_at,
229235
end_at=self._end_at,
@@ -294,6 +300,7 @@ def where(self, field_path, op_string, value) -> "BaseQuery":
294300
orders=self._orders,
295301
limit=self._limit,
296302
offset=self._offset,
303+
limit_to_last=self._limit_to_last,
297304
start_at=self._start_at,
298305
end_at=self._end_at,
299306
all_descendants=self._all_descendants,
@@ -345,21 +352,51 @@ def order_by(self, field_path, direction=ASCENDING) -> "BaseQuery":
345352
field_filters=self._field_filters,
346353
orders=new_orders,
347354
limit=self._limit,
355+
limit_to_last=self._limit_to_last,
348356
offset=self._offset,
349357
start_at=self._start_at,
350358
end_at=self._end_at,
351359
all_descendants=self._all_descendants,
352360
)
353361

354362
def limit(self, count) -> "BaseQuery":
355-
"""Limit a query to return a fixed number of results.
356-
357-
If the current query already has a limit set, this will overwrite it.
363+
"""Limit a query to return at most `count` matching results.
358364
365+
If the current query already has a `limit` set, this will override it.
366+
.. note::
367+
`limit` and `limit_to_last` are mutually exclusive.
368+
Setting `limit` will drop previously set `limit_to_last`.
359369
Args:
360370
count (int): Maximum number of documents to return that match
361371
the query.
372+
Returns:
373+
:class:`~google.cloud.firestore_v1.query.Query`:
374+
A limited query. Acts as a copy of the current query, modified
375+
with the newly added "limit" filter.
376+
"""
377+
return self.__class__(
378+
self._parent,
379+
projection=self._projection,
380+
field_filters=self._field_filters,
381+
orders=self._orders,
382+
limit=count,
383+
limit_to_last=False,
384+
offset=self._offset,
385+
start_at=self._start_at,
386+
end_at=self._end_at,
387+
all_descendants=self._all_descendants,
388+
)
362389

390+
def limit_to_last(self, count):
391+
"""Limit a query to return the last `count` matching results.
392+
If the current query already has a `limit_to_last`
393+
set, this will override it.
394+
.. note::
395+
`limit` and `limit_to_last` are mutually exclusive.
396+
Setting `limit_to_last` will drop previously set `limit`.
397+
Args:
398+
count (int): Maximum number of documents to return that match
399+
the query.
363400
Returns:
364401
:class:`~google.cloud.firestore_v1.query.Query`:
365402
A limited query. Acts as a copy of the current query, modified
@@ -371,6 +408,7 @@ def limit(self, count) -> "BaseQuery":
371408
field_filters=self._field_filters,
372409
orders=self._orders,
373410
limit=count,
411+
limit_to_last=True,
374412
offset=self._offset,
375413
start_at=self._start_at,
376414
end_at=self._end_at,
@@ -398,6 +436,7 @@ def offset(self, num_to_skip) -> "BaseQuery":
398436
field_filters=self._field_filters,
399437
orders=self._orders,
400438
limit=self._limit,
439+
limit_to_last=self._limit_to_last,
401440
offset=num_to_skip,
402441
start_at=self._start_at,
403442
end_at=self._end_at,

google/cloud/firestore_v1/collection.py

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,6 @@
1313
# limitations under the License.
1414

1515
"""Classes for representing collections for the Google Cloud Firestore API."""
16-
import warnings
17-
1816
from google.cloud.firestore_v1.base_collection import (
1917
BaseCollectionReference,
2018
_auto_id,
@@ -121,14 +119,26 @@ def list_documents(self, page_size=None) -> Generator[Any, Any, None]:
121119
)
122120
return (_item_to_document_ref(self, i) for i in iterator)
123121

124-
def get(self, transaction=None) -> Generator[document.DocumentSnapshot, Any, None]:
125-
"""Deprecated alias for :meth:`stream`."""
126-
warnings.warn(
127-
"'Collection.get' is deprecated: please use 'Collection.stream' instead.",
128-
DeprecationWarning,
129-
stacklevel=2,
130-
)
131-
return self.stream(transaction=transaction)
122+
def get(self, transaction=None) -> list:
123+
"""Read the documents in this collection.
124+
125+
This sends a ``RunQuery`` RPC and returns a list of documents
126+
returned in the stream of ``RunQueryResponse`` messages.
127+
128+
Args:
129+
transaction
130+
(Optional[:class:`~google.cloud.firestore_v1.transaction.Transaction`]):
131+
An existing transaction that this query will run in.
132+
133+
If a ``transaction`` is used and it already has write operations
134+
added, this method cannot be used (i.e. read-after-write is not
135+
allowed).
136+
137+
Returns:
138+
list: The documents in this collection that match the query.
139+
"""
140+
query = query_mod.Query(self)
141+
return query.get(transaction=transaction)
132142

133143
def stream(
134144
self, transaction=None

0 commit comments

Comments
 (0)