This repository was archived by the owner on Mar 2, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathbase_query.py
More file actions
1652 lines (1388 loc) · 61.9 KB
/
base_query.py
File metadata and controls
1652 lines (1388 loc) · 61.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2017 Google LLC All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Classes for representing queries for the Google Cloud Firestore API.
A :class:`~google.cloud.firestore_v1.query.Query` can be created directly from
a :class:`~google.cloud.firestore_v1.collection.Collection` and that can be
a more common way to create a query than direct usage of the constructor.
"""
from __future__ import annotations
import abc
import copy
import math
import warnings
from typing import (
TYPE_CHECKING,
Any,
Coroutine,
Dict,
Iterable,
List,
Optional,
Sequence,
Tuple,
Type,
Union,
TypeVar,
)
from google.api_core import retry as retries
from google.protobuf import wrappers_pb2
from google.cloud import firestore_v1
from google.cloud.firestore_v1 import _helpers, document
from google.cloud.firestore_v1 import field_path as field_path_module
from google.cloud.firestore_v1 import transforms
# Types needed only for Type Hints
from google.cloud.firestore_v1.base_document import DocumentSnapshot
from google.cloud.firestore_v1.base_vector_query import DistanceMeasure
from google.cloud.firestore_v1.order import Order
from google.cloud.firestore_v1.types import (
Cursor,
RunQueryResponse,
StructuredQuery,
query,
)
from google.cloud.firestore_v1.vector import Vector
from google.cloud.firestore_v1 import pipeline_expressions
if TYPE_CHECKING: # pragma: NO COVER
from google.cloud.firestore_v1.async_stream_generator import AsyncStreamGenerator
from google.cloud.firestore_v1.field_path import FieldPath
from google.cloud.firestore_v1.query_profile import ExplainOptions
from google.cloud.firestore_v1.query_results import QueryResultsList
from google.cloud.firestore_v1.stream_generator import StreamGenerator
from google.cloud.firestore_v1.pipeline_source import PipelineSource
import datetime
_BAD_DIR_STRING: str
_BAD_OP_NAN: str
_BAD_OP_NULL: str
_BAD_OP_STRING: str
_COMPARISON_OPERATORS: Dict[str, Any]
_EQ_OP: str
_NEQ_OP: str
_INVALID_CURSOR_TRANSFORM: str
_INVALID_WHERE_TRANSFORM: str
_MISMATCH_CURSOR_W_ORDER_BY: str
_MISSING_ORDER_BY: str
_NO_ORDERS_FOR_CURSOR: str
_operator_enum: Any
_EQ_OP = "=="
_NEQ_OP = "!="
_operator_enum = StructuredQuery.FieldFilter.Operator
_COMPARISON_OPERATORS = {
"<": _operator_enum.LESS_THAN,
"<=": _operator_enum.LESS_THAN_OR_EQUAL,
_EQ_OP: _operator_enum.EQUAL,
_NEQ_OP: _operator_enum.NOT_EQUAL,
">=": _operator_enum.GREATER_THAN_OR_EQUAL,
">": _operator_enum.GREATER_THAN,
"array_contains": _operator_enum.ARRAY_CONTAINS,
"in": _operator_enum.IN,
"not-in": _operator_enum.NOT_IN,
"array_contains_any": _operator_enum.ARRAY_CONTAINS_ANY,
}
# set of operators that don't involve equlity comparisons
# will be used in query normalization
_INEQUALITY_OPERATORS = (
_operator_enum.LESS_THAN,
_operator_enum.LESS_THAN_OR_EQUAL,
_operator_enum.GREATER_THAN_OR_EQUAL,
_operator_enum.GREATER_THAN,
_operator_enum.NOT_EQUAL,
_operator_enum.NOT_IN,
)
_BAD_OP_STRING = "Operator string {!r} is invalid. Valid choices are: {}."
_BAD_OP_NAN_NULL = 'Only equality ("==") or not-equal ("!=") filters can be used with None or NaN values'
_INVALID_WHERE_TRANSFORM = "Transforms cannot be used as where values."
_BAD_DIR_STRING = "Invalid direction {!r}. Must be one of {!r} or {!r}."
_INVALID_CURSOR_TRANSFORM = "Transforms cannot be used as cursor values."
_MISSING_ORDER_BY = (
'The "order by" field path {!r} is not present in the cursor data {!r}. '
"All fields sent to ``order_by()`` must be present in the fields "
"if passed to one of ``start_at()`` / ``start_after()`` / "
"``end_before()`` / ``end_at()`` to define a cursor."
)
_NO_ORDERS_FOR_CURSOR = (
"Attempting to create a cursor with no fields to order on. "
"When defining a cursor with one of ``start_at()`` / ``start_after()`` / "
"``end_before()`` / ``end_at()``, all fields in the cursor must "
"come from fields set in ``order_by()``."
)
_MISMATCH_CURSOR_W_ORDER_BY = "The cursor {!r} does not match the order fields {!r}."
_not_passed = object()
QueryType = TypeVar("QueryType", bound="BaseQuery")
class BaseFilter(abc.ABC):
"""Base class for Filters"""
@abc.abstractmethod
def _to_pb(self):
"""Build the protobuf representation based on values in the filter"""
def _validate_opation(op_string, value):
"""
Given an input operator string (e.g, '!='), and a value (e.g. None),
ensure that the operator and value combination is valid, and return
an approproate new operator value. A new operator will be used if
the operaion is a comparison against Null or NaN
Args:
op_string (Optional[str]): the requested operator
value (Any): the value the operator is acting on
Returns:
str | StructuredQuery.UnaryFilter.Operator: operator to use in requests
Raises:
ValueError: if the operator and value combination is invalid
"""
if value is None:
if op_string == _EQ_OP:
return StructuredQuery.UnaryFilter.Operator.IS_NULL
elif op_string == _NEQ_OP:
return StructuredQuery.UnaryFilter.Operator.IS_NOT_NULL
else:
raise ValueError(_BAD_OP_NAN_NULL)
elif _isnan(value):
if op_string == _EQ_OP:
return StructuredQuery.UnaryFilter.Operator.IS_NAN
elif op_string == _NEQ_OP:
return StructuredQuery.UnaryFilter.Operator.IS_NOT_NAN
else:
raise ValueError(_BAD_OP_NAN_NULL)
elif isinstance(value, (transforms.Sentinel, transforms._ValueList)):
raise ValueError(_INVALID_WHERE_TRANSFORM)
else:
return op_string
class FieldFilter(BaseFilter):
"""Class representation of a Field Filter."""
def __init__(self, field_path: str, op_string: str, value: Any | None = None):
self.field_path = field_path
self.value = value
self.op_string = _validate_opation(op_string, value)
def _to_pb(self):
"""Returns the protobuf representation, either a StructuredQuery.UnaryFilter or a StructuredQuery.FieldFilter"""
if self.value is None or _isnan(self.value):
filter_pb = query.StructuredQuery.UnaryFilter(
field=query.StructuredQuery.FieldReference(field_path=self.field_path),
op=self.op_string,
)
else:
filter_pb = query.StructuredQuery.FieldFilter(
field=query.StructuredQuery.FieldReference(field_path=self.field_path),
op=_enum_from_op_string(self.op_string),
value=_helpers.encode_value(self.value),
)
return filter_pb
class BaseCompositeFilter(BaseFilter):
"""Base class for a Composite Filter. (either OR or AND)."""
def __init__(
self,
operator: int = StructuredQuery.CompositeFilter.Operator.OPERATOR_UNSPECIFIED,
filters: list[BaseFilter] | None = None,
):
self.operator = operator
if filters is None:
self.filters = []
else:
self.filters = filters
def __repr__(self):
repr = f"op: {self.operator}\nFilters:"
for filter in self.filters:
repr += f"\n\t{filter}"
return repr
def _to_pb(self):
"""Build the protobuf representation based on values in the Composite Filter."""
filter_pb = StructuredQuery.CompositeFilter(
op=self.operator,
)
for filter in self.filters:
if isinstance(filter, BaseCompositeFilter):
fb = query.StructuredQuery.Filter(composite_filter=filter._to_pb())
else:
fb = _filter_pb(filter._to_pb())
filter_pb.filters.append(fb)
return filter_pb
class Or(BaseCompositeFilter):
"""Class representation of an OR Filter."""
def __init__(self, filters: list[BaseFilter]):
super().__init__(
operator=StructuredQuery.CompositeFilter.Operator.OR, filters=filters
)
class And(BaseCompositeFilter):
"""Class representation of an AND Filter."""
def __init__(self, filters: list[BaseFilter]):
super().__init__(
operator=StructuredQuery.CompositeFilter.Operator.AND, filters=filters
)
class BaseQuery(object):
"""Represents a query to the Firestore API.
Instances of this class are considered immutable: all methods that
would modify an instance instead return a new instance.
Args:
parent (:class:`~google.cloud.firestore_v1.collection.CollectionReference`):
The collection that this query applies to.
projection (Optional[:class:`google.cloud.firestore_v1.\
query.StructuredQuery.Projection`]):
A projection of document fields to limit the query results to.
field_filters (Optional[Tuple[:class:`google.cloud.firestore_v1.\
query.StructuredQuery.FieldFilter`, ...]]):
The filters to be applied in the query.
orders (Optional[Tuple[:class:`google.cloud.firestore_v1.\
query.StructuredQuery.Order`, ...]]):
The "order by" entries to use in the query.
limit (Optional[int]):
The maximum number of documents the query is allowed to return.
limit_to_last (Optional[bool]):
Denotes whether a provided limit is applied to the end of the result set.
offset (Optional[int]):
The number of results to skip.
start_at (Optional[Tuple[dict, bool]]):
Two-tuple of :
* a mapping of fields. Any field that is present in this mapping
must also be present in ``orders``
* an ``after`` flag
The fields and the flag combine to form a cursor used as
a starting point in a query result set. If the ``after``
flag is :data:`True`, the results will start just after any
documents which have fields matching the cursor, otherwise
any matching documents will be included in the result set.
When the query is formed, the document values
will be used in the order given by ``orders``.
end_at (Optional[Tuple[dict, bool]]):
Two-tuple of:
* a mapping of fields. Any field that is present in this mapping
must also be present in ``orders``
* a ``before`` flag
The fields and the flag combine to form a cursor used as
an ending point in a query result set. If the ``before``
flag is :data:`True`, the results will end just before any
documents which have fields matching the cursor, otherwise
any matching documents will be included in the result set.
When the query is formed, the document values
will be used in the order given by ``orders``.
all_descendants (Optional[bool]):
When false, selects only collections that are immediate children
of the `parent` specified in the containing `RunQueryRequest`.
When true, selects all descendant collections.
recursive (Optional[bool]):
When true, returns all documents and all documents in any subcollections
below them. Defaults to false.
"""
ASCENDING = "ASCENDING"
"""str: Sort query results in ascending order on a field."""
DESCENDING = "DESCENDING"
"""str: Sort query results in descending order on a field."""
def __init__(
self,
parent,
projection=None,
field_filters=(),
orders=(),
limit=None,
limit_to_last=False,
offset=None,
start_at=None,
end_at=None,
all_descendants=False,
recursive=False,
) -> None:
self._parent = parent
self._projection = projection
self._field_filters = field_filters
self._orders = orders
self._limit = limit
self._limit_to_last = limit_to_last
self._offset = offset
self._start_at = start_at
self._end_at = end_at
self._all_descendants = all_descendants
self._recursive = recursive
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return (
self._parent == other._parent
and self._projection == other._projection
and self._field_filters == other._field_filters
and self._orders == other._orders
and self._limit == other._limit
and self._limit_to_last == other._limit_to_last
and self._offset == other._offset
and self._start_at == other._start_at
and self._end_at == other._end_at
and self._all_descendants == other._all_descendants
)
@property
def _client(self):
"""The client of the parent collection.
Returns:
:class:`~google.cloud.firestore_v1.client.Client`:
The client that owns this query.
"""
return self._parent._client
def select(self: QueryType, field_paths: Iterable[str]) -> QueryType:
"""Project documents matching query to a limited set of fields.
See :meth:`~google.cloud.firestore_v1.client.Client.field_path` for
more information on **field paths**.
If the current query already has a projection set (i.e. has already
called :meth:`~google.cloud.firestore_v1.query.Query.select`), this
will overwrite it.
Args:
field_paths (Iterable[str, ...]): An iterable of field paths
(``.``-delimited list of field names) to use as a projection
of document fields in the query results.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A "projected" query. Acts as a copy of the current query,
modified with the newly added projection.
Raises:
ValueError: If any ``field_path`` is invalid.
"""
field_paths = list(field_paths)
for field_path in field_paths:
field_path_module.split_field_path(field_path)
new_projection = query.StructuredQuery.Projection(
fields=[
query.StructuredQuery.FieldReference(field_path=field_path)
for field_path in field_paths
]
)
return self._copy(projection=new_projection)
def _copy(
self: QueryType,
*,
projection: Optional[query.StructuredQuery.Projection] | object = _not_passed,
field_filters: Optional[Tuple[query.StructuredQuery.FieldFilter]]
| object = _not_passed,
orders: Optional[Tuple[query.StructuredQuery.Order]] | object = _not_passed,
limit: Optional[int] | object = _not_passed,
limit_to_last: Optional[bool] | object = _not_passed,
offset: Optional[int] | object = _not_passed,
start_at: Optional[Tuple[dict, bool]] | object = _not_passed,
end_at: Optional[Tuple[dict, bool]] | object = _not_passed,
all_descendants: Optional[bool] | object = _not_passed,
recursive: Optional[bool] | object = _not_passed,
) -> QueryType:
return self.__class__(
self._parent,
projection=self._evaluate_param(projection, self._projection),
field_filters=self._evaluate_param(field_filters, self._field_filters),
orders=self._evaluate_param(orders, self._orders),
limit=self._evaluate_param(limit, self._limit),
limit_to_last=self._evaluate_param(limit_to_last, self._limit_to_last),
offset=self._evaluate_param(offset, self._offset),
start_at=self._evaluate_param(start_at, self._start_at),
end_at=self._evaluate_param(end_at, self._end_at),
all_descendants=self._evaluate_param(
all_descendants, self._all_descendants
),
recursive=self._evaluate_param(recursive, self._recursive),
)
def _evaluate_param(self, value, fallback_value):
"""Helper which allows `None` to be passed into `copy` and be set on the
copy instead of being misinterpreted as an unpassed parameter."""
return value if value is not _not_passed else fallback_value
def where(
self: QueryType,
field_path: Optional[str] = None,
op_string: Optional[str] = None,
value=None,
*,
filter=None,
) -> QueryType:
"""Filter the query on a field.
See :meth:`~google.cloud.firestore_v1.client.Client.field_path` for
more information on **field paths**.
Returns a new :class:`~google.cloud.firestore_v1.query.Query` that
filters on a specific field path, according to an operation (e.g.
``==`` or "equals") and a particular value to be paired with that
operation.
Args:
field_path (Optional[str]): A field path (``.``-delimited list of
field names) for the field to filter on.
op_string (Optional[str]): A comparison operation in the form of a string.
Acceptable values are ``<``, ``<=``, ``==``, ``!=``, ``>=``, ``>``,
``in``, ``not-in``, ``array_contains`` and ``array_contains_any``.
value (Any): The value to compare the field against in the filter.
If ``value`` is :data:`None` or a NaN, then ``==`` is the only
allowed operation.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A filtered query. Acts as a copy of the current query,
modified with the newly added filter.
Raises:
ValueError: If
* ``field_path`` is invalid.
* If ``value`` is a NaN or :data:`None` and ``op_string`` is not ``==``.
* FieldFilter was passed without using the filter keyword argument.
* `And` or `Or` was passed without using the filter keyword argument .
* Both the positional arguments and the keyword argument `filter` were passed.
"""
if isinstance(field_path, FieldFilter):
raise ValueError(
"FieldFilter object must be passed using keyword argument 'filter'"
)
if isinstance(field_path, BaseCompositeFilter):
raise ValueError(
"'Or' and 'And' objects must be passed using keyword argument 'filter'"
)
field_path_module.split_field_path(field_path)
new_filters = self._field_filters
if field_path is not None and op_string is not None:
if filter is not None:
raise ValueError(
"Can't pass in both the positional arguments and 'filter' at the same time"
)
warnings.warn(
"Detected filter using positional arguments. Prefer using the 'filter' keyword argument instead.",
UserWarning,
stacklevel=2,
)
op = _validate_opation(op_string, value)
if isinstance(op, StructuredQuery.UnaryFilter.Operator):
filter_pb = query.StructuredQuery.UnaryFilter(
field=query.StructuredQuery.FieldReference(field_path=field_path),
op=op,
)
else:
filter_pb = query.StructuredQuery.FieldFilter(
field=query.StructuredQuery.FieldReference(field_path=field_path),
op=_enum_from_op_string(op_string),
value=_helpers.encode_value(value),
)
new_filters += (filter_pb,)
elif isinstance(filter, BaseFilter):
new_filters += (filter._to_pb(),)
else:
raise ValueError(
"Filter must be provided through positional arguments or the 'filter' keyword argument."
)
return self._copy(field_filters=new_filters)
@staticmethod
def _make_order(field_path, direction) -> StructuredQuery.Order:
"""Helper for :meth:`order_by`."""
return query.StructuredQuery.Order(
field=query.StructuredQuery.FieldReference(field_path=field_path),
direction=_enum_from_direction(direction),
)
def order_by(
self: QueryType, field_path: str, direction: str = ASCENDING
) -> QueryType:
"""Modify the query to add an order clause on a specific field.
See :meth:`~google.cloud.firestore_v1.client.Client.field_path` for
more information on **field paths**.
Successive :meth:`~google.cloud.firestore_v1.query.Query.order_by`
calls will further refine the ordering of results returned by the query
(i.e. the new "order by" fields will be added to existing ones).
Args:
field_path (str): A field path (``.``-delimited list of
field names) on which to order the query results.
direction (Optional[str]): The direction to order by. Must be one
of :attr:`ASCENDING` or :attr:`DESCENDING`, defaults to
:attr:`ASCENDING`.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
An ordered query. Acts as a copy of the current query, modified
with the newly added "order by" constraint.
Raises:
ValueError: If ``field_path`` is invalid.
ValueError: If ``direction`` is not one of :attr:`ASCENDING` or
:attr:`DESCENDING`.
"""
field_path_module.split_field_path(field_path) # raises
order_pb = self._make_order(field_path, direction)
new_orders = self._orders + (order_pb,)
return self._copy(orders=new_orders)
def limit(self: QueryType, count: int) -> QueryType:
"""Limit a query to return at most `count` matching results.
If the current query already has a `limit` set, this will override it.
.. note::
`limit` and `limit_to_last` are mutually exclusive.
Setting `limit` will drop previously set `limit_to_last`.
Args:
count (int): Maximum number of documents to return that match
the query.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A limited query. Acts as a copy of the current query, modified
with the newly added "limit" filter.
"""
return self._copy(limit=count, limit_to_last=False)
def limit_to_last(self: QueryType, count: int) -> QueryType:
"""Limit a query to return the last `count` matching results.
If the current query already has a `limit_to_last`
set, this will override it.
.. note::
`limit` and `limit_to_last` are mutually exclusive.
Setting `limit_to_last` will drop previously set `limit`.
Args:
count (int): Maximum number of documents to return that match
the query.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A limited query. Acts as a copy of the current query, modified
with the newly added "limit" filter.
"""
return self._copy(limit=count, limit_to_last=True)
def _resolve_chunk_size(self, num_loaded: int, chunk_size: int) -> int:
"""Utility function for chunkify."""
if self._limit is not None and (num_loaded + chunk_size) > self._limit:
return max(self._limit - num_loaded, 0)
return chunk_size
def offset(self: QueryType, num_to_skip: int) -> QueryType:
"""Skip to an offset in a query.
If the current query already has specified an offset, this will
overwrite it.
Args:
num_to_skip (int): The number of results to skip at the beginning
of query results. (Must be non-negative.)
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
An offset query. Acts as a copy of the current query, modified
with the newly added "offset" field.
"""
return self._copy(offset=num_to_skip)
def _check_snapshot(self, document_snapshot) -> None:
"""Validate local snapshots for non-collection-group queries.
Raises:
ValueError: for non-collection-group queries, if the snapshot
is from a different collection.
"""
if self._all_descendants:
return
if document_snapshot.reference._path[:-1] != self._parent._path:
raise ValueError("Cannot use snapshot from another collection as a cursor.")
def _cursor_helper(
self: QueryType,
document_fields_or_snapshot: Union[DocumentSnapshot, dict, list, tuple, None],
before: bool,
start: bool,
) -> QueryType:
"""Set values to be used for a ``start_at`` or ``end_at`` cursor.
The values will later be used in a query protobuf.
When the query is sent to the server, the ``document_fields_or_snapshot`` will
be used in the order given by fields set by
:meth:`~google.cloud.firestore_v1.query.Query.order_by`.
Args:
document_fields_or_snapshot
(Union[:class:`~google.cloud.firestore_v1.document.DocumentSnapshot`, dict, list, tuple]):
a document snapshot or a dictionary/list/tuple of fields
representing a query results cursor. A cursor is a collection
of values that represent a position in a query result set.
before (bool): Flag indicating if the document in
``document_fields_or_snapshot`` should (:data:`False`) or
shouldn't (:data:`True`) be included in the result set.
start (Optional[bool]): determines if the cursor is a ``start_at``
cursor (:data:`True`) or an ``end_at`` cursor (:data:`False`).
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A query with cursor. Acts as a copy of the current query, modified
with the newly added "start at" cursor.
"""
if isinstance(document_fields_or_snapshot, tuple):
document_fields_or_snapshot = list(document_fields_or_snapshot)
elif isinstance(document_fields_or_snapshot, document.DocumentSnapshot):
self._check_snapshot(document_fields_or_snapshot)
else:
# NOTE: We copy so that the caller can't modify after calling.
document_fields_or_snapshot = copy.deepcopy(document_fields_or_snapshot)
cursor_pair = document_fields_or_snapshot, before
query_kwargs = {
"projection": self._projection,
"field_filters": self._field_filters,
"orders": self._orders,
"limit": self._limit,
"offset": self._offset,
"all_descendants": self._all_descendants,
}
if start:
query_kwargs["start_at"] = cursor_pair
query_kwargs["end_at"] = self._end_at
else:
query_kwargs["start_at"] = self._start_at
query_kwargs["end_at"] = cursor_pair
return self._copy(**query_kwargs)
def start_at(
self: QueryType,
document_fields_or_snapshot: Union[DocumentSnapshot, dict, list, tuple, None],
) -> QueryType:
"""Start query results at a particular document value.
The result set will **include** the document specified by
``document_fields_or_snapshot``.
If the current query already has specified a start cursor -- either
via this method or
:meth:`~google.cloud.firestore_v1.query.Query.start_after` -- this
will overwrite it.
When the query is sent to the server, the ``document_fields`` will
be used in the order given by fields set by
:meth:`~google.cloud.firestore_v1.query.Query.order_by`.
Args:
document_fields_or_snapshot
(Union[:class:`~google.cloud.firestore_v1.document.DocumentSnapshot`, dict, list, tuple]):
a document snapshot or a dictionary/list/tuple of fields
representing a query results cursor. A cursor is a collection
of values that represent a position in a query result set.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A query with cursor. Acts as
a copy of the current query, modified with the newly added
"start at" cursor.
"""
return self._cursor_helper(document_fields_or_snapshot, before=True, start=True)
def start_after(
self: QueryType,
document_fields_or_snapshot: Union[DocumentSnapshot, dict, list, tuple, None],
) -> QueryType:
"""Start query results after a particular document value.
The result set will **exclude** the document specified by
``document_fields_or_snapshot``.
If the current query already has specified a start cursor -- either
via this method or
:meth:`~google.cloud.firestore_v1.query.Query.start_at` -- this will
overwrite it.
When the query is sent to the server, the ``document_fields_or_snapshot`` will
be used in the order given by fields set by
:meth:`~google.cloud.firestore_v1.query.Query.order_by`.
Args:
document_fields_or_snapshot
(Union[:class:`~google.cloud.firestore_v1.document.DocumentSnapshot`, dict, list, tuple]):
a document snapshot or a dictionary/list/tuple of fields
representing a query results cursor. A cursor is a collection
of values that represent a position in a query result set.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A query with cursor. Acts as a copy of the current query, modified
with the newly added "start after" cursor.
"""
return self._cursor_helper(
document_fields_or_snapshot, before=False, start=True
)
def end_before(
self: QueryType,
document_fields_or_snapshot: Union[DocumentSnapshot, dict, list, tuple, None],
) -> QueryType:
"""End query results before a particular document value.
The result set will **exclude** the document specified by
``document_fields_or_snapshot``.
If the current query already has specified an end cursor -- either
via this method or
:meth:`~google.cloud.firestore_v1.query.Query.end_at` -- this will
overwrite it.
When the query is sent to the server, the ``document_fields_or_snapshot`` will
be used in the order given by fields set by
:meth:`~google.cloud.firestore_v1.query.Query.order_by`.
Args:
document_fields_or_snapshot
(Union[:class:`~google.cloud.firestore_v1.document.DocumentSnapshot`, dict, list, tuple]):
a document snapshot or a dictionary/list/tuple of fields
representing a query results cursor. A cursor is a collection
of values that represent a position in a query result set.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A query with cursor. Acts as a copy of the current query, modified
with the newly added "end before" cursor.
"""
return self._cursor_helper(
document_fields_or_snapshot, before=True, start=False
)
def end_at(
self: QueryType,
document_fields_or_snapshot: Union[DocumentSnapshot, dict, list, tuple, None],
) -> QueryType:
"""End query results at a particular document value.
The result set will **include** the document specified by
``document_fields_or_snapshot``.
If the current query already has specified an end cursor -- either
via this method or
:meth:`~google.cloud.firestore_v1.query.Query.end_before` -- this will
overwrite it.
When the query is sent to the server, the ``document_fields_or_snapshot`` will
be used in the order given by fields set by
:meth:`~google.cloud.firestore_v1.query.Query.order_by`.
Args:
document_fields_or_snapshot
(Union[:class:`~google.cloud.firestore_v1.document.DocumentSnapshot`, dict, list, tuple]):
a document snapshot or a dictionary/list/tuple of fields
representing a query results cursor. A cursor is a collection
of values that represent a position in a query result set.
Returns:
:class:`~google.cloud.firestore_v1.query.Query`:
A query with cursor. Acts as a copy of the current query, modified
with the newly added "end at" cursor.
"""
return self._cursor_helper(
document_fields_or_snapshot, before=False, start=False
)
def _filters_pb(self) -> Optional[StructuredQuery.Filter]:
"""Convert all the filters into a single generic Filter protobuf.
This may be a lone field filter or unary filter, may be a composite
filter or may be :data:`None`.
Returns:
:class:`google.cloud.firestore_v1.types.StructuredQuery.Filter`:
A "generic" filter representing the current query's filters.
"""
num_filters = len(self._field_filters)
if num_filters == 0:
return None
elif num_filters == 1:
filter = self._field_filters[0]
if isinstance(filter, query.StructuredQuery.CompositeFilter):
return query.StructuredQuery.Filter(composite_filter=filter)
else:
return _filter_pb(filter)
else:
composite_filter = query.StructuredQuery.CompositeFilter(
op=StructuredQuery.CompositeFilter.Operator.AND,
)
for filter_ in self._field_filters:
if isinstance(filter_, query.StructuredQuery.CompositeFilter):
composite_filter.filters.append(
query.StructuredQuery.Filter(composite_filter=filter_)
)
else:
composite_filter.filters.append(_filter_pb(filter_))
return query.StructuredQuery.Filter(composite_filter=composite_filter)
@staticmethod
def _normalize_projection(projection) -> StructuredQuery.Projection:
"""Helper: convert field paths to message."""
if projection is not None:
fields = list(projection.fields)
if not fields:
field_ref = query.StructuredQuery.FieldReference(field_path="__name__")
return query.StructuredQuery.Projection(fields=[field_ref])
return projection
def _normalize_orders(self) -> list:
"""Helper: adjust orders based on cursors, where clauses."""
orders = list(self._orders)
_has_snapshot_cursor = False
if self._start_at:
if isinstance(self._start_at[0], document.DocumentSnapshot):
_has_snapshot_cursor = True
if self._end_at:
if isinstance(self._end_at[0], document.DocumentSnapshot):
_has_snapshot_cursor = True
if _has_snapshot_cursor:
# added orders should use direction of last order
last_direction = orders[-1].direction if orders else BaseQuery.ASCENDING
order_keys = [order.field.field_path for order in orders]
for filter_ in self._field_filters:
# FieldFilter.Operator should not compare equal to
# UnaryFilter.Operator, but it does
if isinstance(filter_.op, StructuredQuery.FieldFilter.Operator):
field = filter_.field.field_path
# skip equality filters and filters on fields already ordered
if filter_.op in _INEQUALITY_OPERATORS and field not in order_keys:
orders.append(self._make_order(field, last_direction))
# add __name__ if not already in orders
if "__name__" not in [order.field.field_path for order in orders]:
orders.append(self._make_order("__name__", last_direction))
return orders
def _normalize_cursor(self, cursor, orders) -> Tuple[List, bool] | None:
"""Helper: convert cursor to a list of values based on orders."""
if cursor is None:
return None
if not orders:
raise ValueError(_NO_ORDERS_FOR_CURSOR)
document_fields, before = cursor
order_keys = [order.field.field_path for order in orders]
if isinstance(document_fields, document.DocumentSnapshot):
snapshot = document_fields
document_fields = copy.deepcopy(snapshot._data)
document_fields["__name__"] = snapshot.reference
if isinstance(document_fields, dict):
# Transform to list using orders
values = []
data = document_fields
# It isn't required that all order by have a cursor.
# However, we need to be sure they are specified in order without gaps
for order_key in order_keys[: len(data)]:
try:
if order_key in data:
values.append(data[order_key])
else:
values.append(
field_path_module.get_nested_value(order_key, data)
)
except KeyError:
msg = _MISSING_ORDER_BY.format(order_key, data)
raise ValueError(msg)
document_fields = values
if document_fields and len(document_fields) > len(orders):
msg = _MISMATCH_CURSOR_W_ORDER_BY.format(document_fields, order_keys)
raise ValueError(msg)
_transform_bases = (transforms.Sentinel, transforms._ValueList)
for index, key_field in enumerate(zip(order_keys, document_fields)):
key, field = key_field
if isinstance(field, _transform_bases):
msg = _INVALID_CURSOR_TRANSFORM
raise ValueError(msg)
if key == "__name__" and isinstance(field, str):
document_fields[index] = self._parent.document(field)
return document_fields, before
def _to_protobuf(self) -> StructuredQuery:
"""Convert the current query into the equivalent protobuf.
Returns:
:class:`google.cloud.firestore_v1.types.StructuredQuery`:
The query protobuf.
"""
projection = self._normalize_projection(self._projection)
orders = self._normalize_orders()
start_at = self._normalize_cursor(self._start_at, orders)
end_at = self._normalize_cursor(self._end_at, orders)
query_kwargs = {
"select": projection,
"from_": [
query.StructuredQuery.CollectionSelector(
collection_id=self._parent.id, all_descendants=self._all_descendants
)
],
"where": self._filters_pb(),
"order_by": orders,
"start_at": _cursor_pb(start_at),
"end_at": _cursor_pb(end_at),
}
if self._offset is not None: