-
Notifications
You must be signed in to change notification settings - Fork 63
/
Query.java
1719 lines (1507 loc) · 63.3 KB
/
Query.java
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
*
* 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.
*/
package com.google.cloud.firestore;
import static com.google.common.collect.Lists.reverse;
import static com.google.firestore.v1.StructuredQuery.FieldFilter.Operator.ARRAY_CONTAINS;
import static com.google.firestore.v1.StructuredQuery.FieldFilter.Operator.ARRAY_CONTAINS_ANY;
import static com.google.firestore.v1.StructuredQuery.FieldFilter.Operator.EQUAL;
import static com.google.firestore.v1.StructuredQuery.FieldFilter.Operator.GREATER_THAN;
import static com.google.firestore.v1.StructuredQuery.FieldFilter.Operator.GREATER_THAN_OR_EQUAL;
import static com.google.firestore.v1.StructuredQuery.FieldFilter.Operator.IN;
import static com.google.firestore.v1.StructuredQuery.FieldFilter.Operator.LESS_THAN;
import static com.google.firestore.v1.StructuredQuery.FieldFilter.Operator.LESS_THAN_OR_EQUAL;
import static com.google.firestore.v1.StructuredQuery.FieldFilter.Operator.NOT_EQUAL;
import static com.google.firestore.v1.StructuredQuery.FieldFilter.Operator.NOT_IN;
import com.google.api.core.ApiFuture;
import com.google.api.core.InternalExtensionOnly;
import com.google.api.core.SettableApiFuture;
import com.google.api.gax.rpc.ApiStreamObserver;
import com.google.api.gax.rpc.StatusCode;
import com.google.auto.value.AutoValue;
import com.google.cloud.Timestamp;
import com.google.cloud.firestore.Query.QueryOptions.Builder;
import com.google.cloud.firestore.v1.FirestoreSettings;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.firestore.bundle.BundledQuery;
import com.google.firestore.v1.Cursor;
import com.google.firestore.v1.Document;
import com.google.firestore.v1.RunQueryRequest;
import com.google.firestore.v1.RunQueryResponse;
import com.google.firestore.v1.StructuredQuery;
import com.google.firestore.v1.StructuredQuery.CollectionSelector;
import com.google.firestore.v1.StructuredQuery.CompositeFilter;
import com.google.firestore.v1.StructuredQuery.FieldReference;
import com.google.firestore.v1.StructuredQuery.Filter;
import com.google.firestore.v1.StructuredQuery.Order;
import com.google.firestore.v1.Value;
import com.google.protobuf.ByteString;
import com.google.protobuf.Int32Value;
import io.grpc.Status;
import io.opencensus.trace.AttributeValue;
import io.opencensus.trace.Tracing;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* A Query which you can read or listen to. You can also construct refined Query objects by adding
* filters and ordering.
*/
@InternalExtensionOnly
public class Query {
final FirestoreRpcContext<?> rpcContext;
final QueryOptions options;
/** The direction of a sort. */
public enum Direction {
ASCENDING(StructuredQuery.Direction.ASCENDING),
DESCENDING(StructuredQuery.Direction.DESCENDING);
private final StructuredQuery.Direction direction;
Direction(StructuredQuery.Direction direction) {
this.direction = direction;
}
StructuredQuery.Direction getDirection() {
return direction;
}
}
abstract static class FieldFilter {
protected final FieldReference fieldReference;
FieldFilter(FieldReference fieldReference) {
this.fieldReference = fieldReference;
}
static FieldFilter fromProto(StructuredQuery.Filter filter) {
Preconditions.checkArgument(
!filter.hasCompositeFilter(), "Cannot deserialize nested composite filters");
if (filter.hasFieldFilter()) {
return new ComparisonFilter(
filter.getFieldFilter().getField(),
filter.getFieldFilter().getOp(),
filter.getFieldFilter().getValue());
} else {
Preconditions.checkState(filter.hasUnaryFilter(), "Expected unary of field filter");
return new UnaryFilter(filter.getUnaryFilter().getField(), filter.getUnaryFilter().getOp());
}
}
abstract boolean isInequalityFilter();
abstract Filter toProto();
}
private static class UnaryFilter extends FieldFilter {
private final StructuredQuery.UnaryFilter.Operator operator;
UnaryFilter(FieldReference fieldReference, StructuredQuery.UnaryFilter.Operator operator) {
super(fieldReference);
this.operator = operator;
}
@Override
boolean isInequalityFilter() {
return false;
}
Filter toProto() {
Filter.Builder result = Filter.newBuilder();
result.getUnaryFilterBuilder().setField(fieldReference).setOp(operator);
return result.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof UnaryFilter)) {
return false;
}
UnaryFilter other = (UnaryFilter) o;
return Objects.equals(fieldReference, other.fieldReference)
&& Objects.equals(operator, other.operator);
}
}
static class ComparisonFilter extends FieldFilter {
final StructuredQuery.FieldFilter.Operator operator;
final Value value;
ComparisonFilter(
FieldReference fieldReference, StructuredQuery.FieldFilter.Operator operator, Value value) {
super(fieldReference);
this.value = value;
this.operator = operator;
}
@Override
boolean isInequalityFilter() {
return operator.equals(GREATER_THAN)
|| operator.equals(GREATER_THAN_OR_EQUAL)
|| operator.equals(LESS_THAN)
|| operator.equals(LESS_THAN_OR_EQUAL);
}
Filter toProto() {
Filter.Builder result = Filter.newBuilder();
result.getFieldFilterBuilder().setField(fieldReference).setValue(value).setOp(operator);
return result.build();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ComparisonFilter)) {
return false;
}
ComparisonFilter other = (ComparisonFilter) o;
return Objects.equals(fieldReference, other.fieldReference)
&& Objects.equals(operator, other.operator)
&& Objects.equals(value, other.value);
}
}
static final class FieldOrder {
private final FieldReference fieldReference;
private final Direction direction;
FieldOrder(FieldReference fieldReference, Direction direction) {
this.fieldReference = fieldReference;
this.direction = direction;
}
Order toProto() {
Order.Builder result = Order.newBuilder();
result.setField(fieldReference);
result.setDirection(direction.getDirection());
return result.build();
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof FieldOrder)) {
return false;
}
FieldOrder filter = (FieldOrder) o;
return Objects.equals(toProto(), filter.toProto());
}
}
/** Denotes whether a provided limit is applied to the beginning or the end of the result set. */
enum LimitType {
First,
Last
}
/** Options that define a Firestore Query. */
@AutoValue
abstract static class QueryOptions {
abstract ResourcePath getParentPath();
abstract String getCollectionId();
abstract boolean getAllDescendants();
abstract @Nullable Integer getLimit();
abstract LimitType getLimitType();
abstract @Nullable Integer getOffset();
abstract @Nullable Cursor getStartCursor();
abstract @Nullable Cursor getEndCursor();
abstract ImmutableList<FieldFilter> getFieldFilters();
abstract ImmutableList<FieldOrder> getFieldOrders();
abstract ImmutableList<FieldReference> getFieldProjections();
static Builder builder() {
return new AutoValue_Query_QueryOptions.Builder()
.setAllDescendants(false)
.setLimitType(LimitType.First)
.setFieldOrders(ImmutableList.<FieldOrder>of())
.setFieldFilters(ImmutableList.<FieldFilter>of())
.setFieldProjections(ImmutableList.<FieldReference>of());
}
abstract Builder toBuilder();
@AutoValue.Builder
abstract static class Builder {
abstract Builder setParentPath(ResourcePath value);
abstract Builder setCollectionId(String value);
abstract Builder setAllDescendants(boolean value);
abstract Builder setLimit(Integer value);
abstract Builder setLimitType(LimitType value);
abstract Builder setOffset(Integer value);
abstract Builder setStartCursor(@Nullable Cursor value);
abstract Builder setEndCursor(@Nullable Cursor value);
abstract Builder setFieldFilters(ImmutableList<FieldFilter> value);
abstract Builder setFieldOrders(ImmutableList<FieldOrder> value);
abstract Builder setFieldProjections(ImmutableList<FieldReference> value);
abstract QueryOptions build();
}
}
/** Creates a query for documents in a single collection */
Query(FirestoreRpcContext<?> rpcContext, ResourcePath path) {
this(
rpcContext,
QueryOptions.builder()
.setParentPath(path.getParent())
.setCollectionId(path.getId())
.build());
}
protected Query(FirestoreRpcContext<?> rpcContext, QueryOptions queryOptions) {
this.rpcContext = rpcContext;
this.options = queryOptions;
}
/**
* Gets the Firestore instance associated with this query.
*
* @return The Firestore instance associated with this query.
*/
@Nonnull
public Firestore getFirestore() {
return rpcContext.getFirestore();
}
/** Checks whether the provided object is NULL or NaN. */
private static boolean isUnaryComparison(@Nullable Object value) {
return value == null || value.equals(Double.NaN) || value.equals(Float.NaN);
}
/** Computes the backend ordering semantics for DocumentSnapshot cursors. */
private ImmutableList<FieldOrder> createImplicitOrderBy() {
List<FieldOrder> implicitOrders = new ArrayList<>(options.getFieldOrders());
boolean hasDocumentId = false;
if (implicitOrders.isEmpty()) {
// If no explicit ordering is specified, use the first inequality to define an implicit order.
for (FieldFilter fieldFilter : options.getFieldFilters()) {
if (fieldFilter.isInequalityFilter()) {
implicitOrders.add(new FieldOrder(fieldFilter.fieldReference, Direction.ASCENDING));
break;
}
}
} else {
for (FieldOrder fieldOrder : options.getFieldOrders()) {
if (FieldPath.isDocumentId(fieldOrder.fieldReference.getFieldPath())) {
hasDocumentId = true;
}
}
}
if (!hasDocumentId) {
// Add implicit sorting by name, using the last specified direction.
Direction lastDirection =
implicitOrders.isEmpty()
? Direction.ASCENDING
: implicitOrders.get(implicitOrders.size() - 1).direction;
implicitOrders.add(new FieldOrder(FieldPath.documentId().toProto(), lastDirection));
}
return ImmutableList.<FieldOrder>builder().addAll(implicitOrders).build();
}
private Cursor createCursor(
ImmutableList<FieldOrder> order, DocumentSnapshot documentSnapshot, boolean before) {
List<Object> fieldValues = new ArrayList<>();
for (FieldOrder fieldOrder : order) {
String path = fieldOrder.fieldReference.getFieldPath();
if (FieldPath.isDocumentId(path)) {
fieldValues.add(documentSnapshot.getReference());
} else {
FieldPath fieldPath = FieldPath.fromDotSeparatedString(path);
Preconditions.checkArgument(
documentSnapshot.contains(fieldPath),
"Field '%s' is missing in the provided DocumentSnapshot. Please provide a document "
+ "that contains values for all specified orderBy() and where() constraints.");
fieldValues.add(documentSnapshot.get(fieldPath));
}
}
return createCursor(order, fieldValues.toArray(), before);
}
private Cursor createCursor(List<FieldOrder> order, Object[] fieldValues, boolean before) {
Cursor.Builder result = Cursor.newBuilder();
Preconditions.checkState(
fieldValues.length != 0, "At least one cursor value must be specified.");
Preconditions.checkState(
fieldValues.length <= order.size(),
"Too many cursor values specified. The specified values must match the "
+ "orderBy() constraints of the query.");
Iterator<FieldOrder> fieldOrderIterator = order.iterator();
for (Object fieldValue : fieldValues) {
Object sanitizedValue;
FieldReference fieldReference = fieldOrderIterator.next().fieldReference;
if (FieldPath.isDocumentId(fieldReference.getFieldPath())) {
sanitizedValue = convertReference(fieldValue);
} else {
sanitizedValue = CustomClassMapper.serialize(fieldValue);
}
Value encodedValue = encodeValue(fieldReference, sanitizedValue);
if (encodedValue == null) {
throw FirestoreException.forInvalidArgument(
"Cannot use FieldValue.delete() or FieldValue.serverTimestamp() in a query boundary");
}
result.addValues(encodedValue);
}
result.setBefore(before);
return result.build();
}
/**
* Validates that a value used with FieldValue.documentId() is either a string or a
* DocumentReference that is part of the query`s result set. Throws a validation error or returns
* a DocumentReference that can directly be used in the Query.
*/
private Object convertReference(Object fieldValue) {
ResourcePath basePath =
options.getAllDescendants()
? options.getParentPath()
: options.getParentPath().append(options.getCollectionId());
DocumentReference reference;
if (fieldValue instanceof String) {
reference = new DocumentReference(rpcContext, basePath.append((String) fieldValue));
} else if (fieldValue instanceof DocumentReference) {
reference = (DocumentReference) fieldValue;
} else {
throw new IllegalArgumentException(
String.format(
"The corresponding value for FieldPath.documentId() must be a String or a "
+ "DocumentReference, but was: %s.",
fieldValue.toString()));
}
if (!basePath.isPrefixOf(reference.getResourcePath())) {
throw new IllegalArgumentException(
String.format(
"'%s' is not part of the query result set and cannot be used as a query boundary.",
reference.getPath()));
}
if (!options.getAllDescendants() && !reference.getParent().getResourcePath().equals(basePath)) {
throw new IllegalArgumentException(
String.format(
"Only a direct child can be used as a query boundary. Found: '%s'",
reference.getPath()));
}
return reference;
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and the value should be equal to the specified value.
*
* @param field The name of the field to compare.
* @param value The value for comparison.
* @return The created Query.
*/
@Nonnull
public Query whereEqualTo(@Nonnull String field, @Nullable Object value) {
return whereEqualTo(FieldPath.fromDotSeparatedString(field), value);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and the value should be equal to the specified value.
*
* @param fieldPath The path of the field to compare.
* @param value The value for comparison.
* @return The created Query.
*/
@Nonnull
public Query whereEqualTo(@Nonnull FieldPath fieldPath, @Nullable Object value) {
Preconditions.checkState(
options.getStartCursor() == null && options.getEndCursor() == null,
"Cannot call whereEqualTo() after defining a boundary with startAt(), "
+ "startAfter(), endBefore() or endAt().");
if (isUnaryComparison(value)) {
Builder newOptions = options.toBuilder();
StructuredQuery.UnaryFilter.Operator op =
value == null
? StructuredQuery.UnaryFilter.Operator.IS_NULL
: StructuredQuery.UnaryFilter.Operator.IS_NAN;
UnaryFilter newFieldFilter = new UnaryFilter(fieldPath.toProto(), op);
newOptions.setFieldFilters(append(options.getFieldFilters(), newFieldFilter));
return new Query(rpcContext, newOptions.build());
} else {
return whereHelper(fieldPath, EQUAL, value);
}
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and its value does not equal the specified value.
*
* @param field The name of the field to compare.
* @param value The value for comparison.
* @return The created Query.
*/
@Nonnull
public Query whereNotEqualTo(@Nonnull String field, @Nullable Object value) {
return whereNotEqualTo(FieldPath.fromDotSeparatedString(field), value);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and the value does not equal the specified value.
*
* @param fieldPath The path of the field to compare.
* @param value The value for comparison.
* @return The created Query.
*/
@Nonnull
public Query whereNotEqualTo(@Nonnull FieldPath fieldPath, @Nullable Object value) {
Preconditions.checkState(
options.getStartCursor() == null && options.getEndCursor() == null,
"Cannot call whereNotEqualTo() after defining a boundary with startAt(), "
+ "startAfter(), endBefore() or endAt().");
if (isUnaryComparison(value)) {
Builder newOptions = options.toBuilder();
StructuredQuery.UnaryFilter.Operator op =
value == null
? StructuredQuery.UnaryFilter.Operator.IS_NOT_NULL
: StructuredQuery.UnaryFilter.Operator.IS_NOT_NAN;
UnaryFilter newFieldFilter = new UnaryFilter(fieldPath.toProto(), op);
newOptions.setFieldFilters(append(options.getFieldFilters(), newFieldFilter));
return new Query(rpcContext, newOptions.build());
} else {
return whereHelper(fieldPath, NOT_EQUAL, value);
}
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and the value should be less than the specified value.
*
* @param field The name of the field to compare.
* @param value The value for comparison.
* @return The created Query.
*/
@Nonnull
public Query whereLessThan(@Nonnull String field, @Nonnull Object value) {
return whereLessThan(FieldPath.fromDotSeparatedString(field), value);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and the value should be less than the specified value.
*
* @param fieldPath The path of the field to compare.
* @param value The value for comparison.
* @return The created Query.
*/
@Nonnull
public Query whereLessThan(@Nonnull FieldPath fieldPath, @Nonnull Object value) {
Preconditions.checkState(
options.getStartCursor() == null && options.getEndCursor() == null,
"Cannot call whereLessThan() after defining a boundary with startAt(), "
+ "startAfter(), endBefore() or endAt().");
return whereHelper(fieldPath, LESS_THAN, value);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and the value should be less or equal to the specified value.
*
* @param field The name of the field to compare.
* @param value The value for comparison.
* @return The created Query.
*/
@Nonnull
public Query whereLessThanOrEqualTo(@Nonnull String field, @Nonnull Object value) {
return whereLessThanOrEqualTo(FieldPath.fromDotSeparatedString(field), value);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and the value should be less or equal to the specified value.
*
* @param fieldPath The path of the field to compare.
* @param value The value for comparison.
* @return The created Query.
*/
@Nonnull
public Query whereLessThanOrEqualTo(@Nonnull FieldPath fieldPath, @Nonnull Object value) {
Preconditions.checkState(
options.getStartCursor() == null && options.getEndCursor() == null,
"Cannot call whereLessThanOrEqualTo() after defining a boundary with startAt(), "
+ "startAfter(), endBefore() or endAt().");
return whereHelper(fieldPath, LESS_THAN_OR_EQUAL, value);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and the value should be greater than the specified value.
*
* @param field The name of the field to compare.
* @param value The value for comparison.
* @return The created Query.
*/
@Nonnull
public Query whereGreaterThan(@Nonnull String field, @Nonnull Object value) {
return whereGreaterThan(FieldPath.fromDotSeparatedString(field), value);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and the value should be greater than the specified value.
*
* @param fieldPath The path of the field to compare.
* @param value The value for comparison.
* @return The created Query.
*/
@Nonnull
public Query whereGreaterThan(@Nonnull FieldPath fieldPath, @Nonnull Object value) {
Preconditions.checkState(
options.getStartCursor() == null && options.getEndCursor() == null,
"Cannot call whereGreaterThan() after defining a boundary with startAt(), "
+ "startAfter(), endBefore() or endAt().");
return whereHelper(fieldPath, GREATER_THAN, value);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and the value should be greater than or equal to the specified value.
*
* @param field The name of the field to compare.
* @param value The value for comparison.
* @return The created Query.
*/
@Nonnull
public Query whereGreaterThanOrEqualTo(@Nonnull String field, @Nonnull Object value) {
return whereGreaterThanOrEqualTo(FieldPath.fromDotSeparatedString(field), value);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and the value should be greater than or equal to the specified value.
*
* @param fieldPath The path of the field to compare.
* @param value The value for comparison.
* @return The created Query.
*/
@Nonnull
public Query whereGreaterThanOrEqualTo(@Nonnull FieldPath fieldPath, @Nonnull Object value) {
Preconditions.checkState(
options.getStartCursor() == null && options.getEndCursor() == null,
"Cannot call whereGreaterThanOrEqualTo() after defining a boundary with startAt(), "
+ "startAfter(), endBefore() or endAt().");
return whereHelper(fieldPath, GREATER_THAN_OR_EQUAL, value);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field, the value must be an array, and that the array must contain the provided
* value.
*
* <p>A Query can have only one whereArrayContains() filter and it cannot be combined with
* whereArrayContainsAny().
*
* @param field The name of the field containing an array to search
* @param value The value that must be contained in the array
* @return The created Query.
*/
@Nonnull
public Query whereArrayContains(@Nonnull String field, @Nonnull Object value) {
return whereArrayContains(FieldPath.fromDotSeparatedString(field), value);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field, the value must be an array, and that the array must contain the provided
* value.
*
* <p>A Query can have only one whereArrayContains() filter and it cannot be combined with
* whereArrayContainsAny().
*
* @param fieldPath The path of the field containing an array to search
* @param value The value that must be contained in the array
* @return The created Query.
*/
@Nonnull
public Query whereArrayContains(@Nonnull FieldPath fieldPath, @Nonnull Object value) {
Preconditions.checkState(
options.getStartCursor() == null && options.getEndCursor() == null,
"Cannot call whereArrayContains() after defining a boundary with startAt(), "
+ "startAfter(), endBefore() or endAt().");
return whereHelper(fieldPath, ARRAY_CONTAINS, value);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field, the value must be an array, and that the array must contain at least one value
* from the provided list.
*
* <p>A Query can have only one whereArrayContainsAny() filter and it cannot be combined with
* whereArrayContains() or whereIn().
*
* @param field The name of the field containing an array to search.
* @param values A list that contains the values to match.
* @return The created Query.
*/
@Nonnull
public Query whereArrayContainsAny(
@Nonnull String field, @Nonnull List<? extends Object> values) {
Preconditions.checkState(
options.getStartCursor() == null && options.getEndCursor() == null,
"Cannot call whereArrayContainsAny() after defining a boundary with startAt(), "
+ "startAfter(), endBefore() or endAt().");
return whereHelper(FieldPath.fromDotSeparatedString(field), ARRAY_CONTAINS_ANY, values);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field, the value must be an array, and that the array must contain at least one value
* from the provided list.
*
* <p>A Query can have only one whereArrayContainsAny() filter and it cannot be combined with
* whereArrayContains() or whereIn().
*
* @param fieldPath The path of the field containing an array to search.
* @param values A list that contains the values to match.
* @return The created Query.
*/
@Nonnull
public Query whereArrayContainsAny(
@Nonnull FieldPath fieldPath, @Nonnull List<? extends Object> values) {
Preconditions.checkState(
options.getStartCursor() == null && options.getEndCursor() == null,
"Cannot call whereArrayContainsAny() after defining a boundary with startAt(), "
+ "startAfter(), endBefore() or endAt().");
return whereHelper(fieldPath, ARRAY_CONTAINS_ANY, values);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and the value must equal one of the values from the provided list.
*
* <p>A Query can have only one whereIn() filter, and it cannot be combined with
* whereArrayContainsAny().
*
* @param field The name of the field to search.
* @param values A list that contains the values to match.
* @return The created Query.
*/
@Nonnull
public Query whereIn(@Nonnull String field, @Nonnull List<? extends Object> values) {
Preconditions.checkState(
options.getStartCursor() == null && options.getEndCursor() == null,
"Cannot call whereIn() after defining a boundary with startAt(), "
+ "startAfter(), endBefore() or endAt().");
return whereHelper(FieldPath.fromDotSeparatedString(field), IN, values);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and the value must equal one of the values from the provided list.
*
* <p>A Query can have only one whereIn() filter, and it cannot be combined with
* whereArrayContainsAny().
*
* @param fieldPath The path of the field to search.
* @param values A list that contains the values to match.
* @return The created Query.
*/
@Nonnull
public Query whereIn(@Nonnull FieldPath fieldPath, @Nonnull List<? extends Object> values) {
Preconditions.checkState(
options.getStartCursor() == null && options.getEndCursor() == null,
"Cannot call whereIn() after defining a boundary with startAt(), "
+ "startAfter(), endBefore() or endAt().");
return whereHelper(fieldPath, IN, values);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and the value does not equal any of the values from the provided list.
*
* <p>A Query can have only one whereNotIn() filter and it cannot be combined with
* whereArrayContains(), whereArrayContainsAny(), whereIn(), or whereNotEqualTo().
*
* @param field The name of the field to search.
* @param values The list that contains the values to match.
* @return The created Query.
*/
@Nonnull
public Query whereNotIn(@Nonnull String field, @Nonnull List<? extends Object> values) {
Preconditions.checkState(
options.getStartCursor() == null && options.getEndCursor() == null,
"Cannot call whereNotIn() after defining a boundary with startAt(), "
+ "startAfter(), endBefore() or endAt().");
return whereHelper(FieldPath.fromDotSeparatedString(field), NOT_IN, values);
}
/**
* Creates and returns a new Query with the additional filter that documents must contain the
* specified field and the value does not equal any of the values from the provided list.
*
* <p>A Query can have only one whereNotIn() filter, and it cannot be combined with
* whereArrayContains(), whereArrayContainsAny(), whereIn(), or whereNotEqualTo().
*
* @param fieldPath The path of the field to search.
* @param values The list that contains the values to match.
* @return The created Query.
*/
@Nonnull
public Query whereNotIn(@Nonnull FieldPath fieldPath, @Nonnull List<? extends Object> values) {
Preconditions.checkState(
options.getStartCursor() == null && options.getEndCursor() == null,
"Cannot call whereNotIn() after defining a boundary with startAt(), "
+ "startAfter(), endBefore() or endAt().");
return whereHelper(fieldPath, NOT_IN, values);
}
private Query whereHelper(
FieldPath fieldPath, StructuredQuery.FieldFilter.Operator operator, Object value) {
Preconditions.checkArgument(
!isUnaryComparison(value),
"Cannot use '%s' in field comparison. Use an equality filter instead.",
value);
if (fieldPath.equals(FieldPath.DOCUMENT_ID)) {
if (operator == ARRAY_CONTAINS || operator == ARRAY_CONTAINS_ANY) {
throw new IllegalArgumentException(
String.format(
"Invalid query. You cannot perform '%s' queries on FieldPath.documentId().",
operator.toString()));
} else if (operator == IN | operator == NOT_IN) {
if (!(value instanceof List) || ((List<?>) value).isEmpty()) {
throw new IllegalArgumentException(
String.format(
"Invalid Query. A non-empty array is required for '%s' filters.",
operator.toString()));
}
List<Object> referenceList = new ArrayList<>();
for (Object arrayValue : (List<Object>) value) {
Object convertedValue = this.convertReference(arrayValue);
referenceList.add(convertedValue);
}
value = referenceList;
} else {
value = this.convertReference(value);
}
}
Builder newOptions = options.toBuilder();
ComparisonFilter newFieldFilter =
new ComparisonFilter(fieldPath.toProto(), operator, encodeValue(fieldPath, value));
newOptions.setFieldFilters(append(options.getFieldFilters(), newFieldFilter));
return new Query(rpcContext, newOptions.build());
}
/**
* Creates and returns a new Query that's additionally sorted by the specified field.
*
* @param field The field to sort by.
* @return The created Query.
*/
@Nonnull
public Query orderBy(@Nonnull String field) {
return orderBy(FieldPath.fromDotSeparatedString(field), Direction.ASCENDING);
}
/**
* Creates and returns a new Query that's additionally sorted by the specified field.
*
* @param fieldPath The field to sort by.
* @return The created Query.
*/
@Nonnull
public Query orderBy(@Nonnull FieldPath fieldPath) {
return orderBy(fieldPath, Direction.ASCENDING);
}
/**
* Creates and returns a new Query that's additionally sorted by the specified field, optionally
* in descending order instead of ascending.
*
* @param field The field to sort by.
* @param direction The direction to sort.
* @return The created Query.
*/
@Nonnull
public Query orderBy(@Nonnull String field, @Nonnull Direction direction) {
return orderBy(FieldPath.fromDotSeparatedString(field), direction);
}
/**
* Creates and returns a new Query that's additionally sorted by the specified field, optionally
* in descending order instead of ascending.
*
* @param fieldPath The field to sort by.
* @param direction The direction to sort.
* @return The created Query.
*/
@Nonnull
public Query orderBy(@Nonnull FieldPath fieldPath, @Nonnull Direction direction) {
Preconditions.checkState(
options.getStartCursor() == null && options.getEndCursor() == null,
"Cannot specify an orderBy() constraint after calling startAt(), "
+ "startAfter(), endBefore() or endAt().");
Builder newOptions = options.toBuilder();
FieldOrder newFieldOrder = new FieldOrder(fieldPath.toProto(), direction);
newOptions.setFieldOrders(append(options.getFieldOrders(), newFieldOrder));
return new Query(rpcContext, newOptions.build());
}
/**
* Creates and returns a new Query that only returns the first matching documents.
*
* @param limit The maximum number of items to return.
* @return The created Query.
*/
@Nonnull
public Query limit(int limit) {
return new Query(
rpcContext, options.toBuilder().setLimit(limit).setLimitType(LimitType.First).build());
}
/**
* Creates and returns a new Query that only returns the last matching documents.
*
* <p>You must specify at least one orderBy clause for limitToLast queries. Otherwise, an {@link
* java.lang.IllegalStateException} is thrown during execution.
*
* <p>Results for limitToLast() queries are only available once all documents are received. Hence,
* limitToLast() queries cannot be streamed via the {@link #stream(ApiStreamObserver)} API.
*
* @param limit the maximum number of items to return
* @return the created Query
*/
@Nonnull
public Query limitToLast(int limit) {
return new Query(
rpcContext, options.toBuilder().setLimit(limit).setLimitType(LimitType.Last).build());
}
/**
* Creates and returns a new Query that skips the first n results.
*
* @param offset The number of items to skip.
* @return The created Query.
*/
@Nonnull
public Query offset(int offset) {
return new Query(rpcContext, options.toBuilder().setOffset(offset).build());
}
/**
* Creates and returns a new Query that starts at the provided document (inclusive). The starting
* position is relative to the order of the query. The document must contain all of the fields
* provided in the orderBy of this query.
*
* @param snapshot The snapshot of the document to start at.
* @return The created Query.
*/
@Nonnull
public Query startAt(@Nonnull DocumentSnapshot snapshot) {
ImmutableList<FieldOrder> fieldOrders = createImplicitOrderBy();
Cursor cursor = createCursor(fieldOrders, snapshot, true);
Builder newOptions = options.toBuilder();
newOptions.setFieldOrders(fieldOrders);
newOptions.setStartCursor(cursor);
return new Query(rpcContext, newOptions.build());
}
/**
* Creates and returns a new Query that starts at the provided fields relative to the order of the
* query. The order of the field values must match the order of the order by clauses of the query.
*
* @param fieldValues The field values to start this query at, in order of the query's order by.
* @return The created Query.
*/
@Nonnull
public Query startAt(Object... fieldValues) {
ImmutableList<FieldOrder> fieldOrders =
fieldValues.length == 1 && fieldValues[0] instanceof DocumentReference
? createImplicitOrderBy()
: options.getFieldOrders();
Cursor cursor = createCursor(fieldOrders, fieldValues, true);
Builder newOptions = options.toBuilder();
newOptions.setFieldOrders(fieldOrders);
newOptions.setStartCursor(cursor);
return new Query(rpcContext, newOptions.build());