aboutsummaryrefslogtreecommitdiffhomepage
path: root/Firestore/Source/Core/FSTQuery.mm
blob: abec474688b45be6cd902aaaef0645b18b76ebe4 (plain)
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
/*
 * Copyright 2017 Google
 *
 * 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.
 */

#import "Firestore/Source/Core/FSTQuery.h"

#include <memory>
#include <string>
#include <utility>

#import "Firestore/Source/API/FIRFirestore+Internal.h"
#import "Firestore/Source/Model/FSTDocument.h"
#import "Firestore/Source/Model/FSTFieldValue.h"

#include "Firestore/core/src/firebase/firestore/model/document_key.h"
#include "Firestore/core/src/firebase/firestore/model/field_path.h"
#include "Firestore/core/src/firebase/firestore/model/resource_path.h"
#include "Firestore/core/src/firebase/firestore/util/hard_assert.h"
#include "Firestore/core/src/firebase/firestore/util/hashing.h"
#include "Firestore/core/src/firebase/firestore/util/string_apple.h"

namespace util = firebase::firestore::util;
using firebase::firestore::model::DocumentKey;
using firebase::firestore::model::FieldPath;
using firebase::firestore::model::ResourcePath;

NS_ASSUME_NONNULL_BEGIN

#pragma mark - FSTRelationFilterOperator functions

/**
 * Returns the reverse order (i.e. Ascending => Descending) etc.
 */
static constexpr NSComparisonResult ReverseOrder(NSComparisonResult result) {
  return static_cast<NSComparisonResult>(-static_cast<NSInteger>(result));
}

NSString *FSTStringFromQueryRelationOperator(FSTRelationFilterOperator filterOperator) {
  switch (filterOperator) {
    case FSTRelationFilterOperatorLessThan:
      return @"<";
    case FSTRelationFilterOperatorLessThanOrEqual:
      return @"<=";
    case FSTRelationFilterOperatorEqual:
      return @"==";
    case FSTRelationFilterOperatorGreaterThanOrEqual:
      return @">=";
    case FSTRelationFilterOperatorGreaterThan:
      return @">";
    case FSTRelationFilterOperatorArrayContains:
      return @"array_contains";
    default:
      HARD_FAIL("Unknown FSTRelationFilterOperator %s", filterOperator);
  }
}

#pragma mark - FSTRelationFilter

@interface FSTRelationFilter () {
  /** The left hand side of the relation. A path into a document field. */
  firebase::firestore::model::FieldPath _field;
}

/**
 * Initializes the receiver relation filter.
 *
 * @param field A path to a field in the document to filter on. The LHS of the expression.
 * @param filterOperator The binary operator to apply.
 * @param value A constant value to compare @a field to. The RHS of the expression.
 */
- (instancetype)initWithField:(FieldPath)field
               filterOperator:(FSTRelationFilterOperator)filterOperator
                        value:(FSTFieldValue *)value NS_DESIGNATED_INITIALIZER;

/** Returns YES if @a document matches the receiver's constraint. */
- (BOOL)matchesDocument:(FSTDocument *)document;

/**
 * A canonical string identifying the filter. Two different instances of equivalent filters will
 * return the same canonicalID.
 */
- (NSString *)canonicalID;

@end

@implementation FSTRelationFilter

#pragma mark - Constructor methods

+ (instancetype)filterWithField:(FieldPath)field
                 filterOperator:(FSTRelationFilterOperator)filterOperator
                          value:(FSTFieldValue *)value {
  return [[FSTRelationFilter alloc] initWithField:std::move(field)
                                   filterOperator:filterOperator
                                            value:value];
}

- (instancetype)initWithField:(FieldPath)field
               filterOperator:(FSTRelationFilterOperator)filterOperator
                        value:(FSTFieldValue *)value {
  self = [super init];
  if (self) {
    _field = std::move(field);
    _filterOperator = filterOperator;
    _value = value;
  }
  return self;
}

#pragma mark - Public Methods

- (BOOL)isInequality {
  return self.filterOperator != FSTRelationFilterOperatorEqual &&
         self.filterOperator != FSTRelationFilterOperatorArrayContains;
}

- (const firebase::firestore::model::FieldPath &)field {
  return _field;
}

#pragma mark - NSObject methods

- (NSString *)description {
  return [NSString stringWithFormat:@"%s %@ %@", _field.CanonicalString().c_str(),
                                    FSTStringFromQueryRelationOperator(self.filterOperator),
                                    self.value];
}

- (BOOL)isEqual:(id)other {
  if (self == other) {
    return YES;
  }
  if (![other isKindOfClass:[FSTRelationFilter class]]) {
    return NO;
  }
  return [self isEqualToFilter:(FSTRelationFilter *)other];
}

#pragma mark - Private methods

- (BOOL)matchesDocument:(FSTDocument *)document {
  if (_field.IsKeyFieldPath()) {
    HARD_ASSERT([self.value isKindOfClass:[FSTReferenceValue class]],
                "Comparing on key, but filter value not a FSTReferenceValue.");
    HARD_ASSERT(self.filterOperator != FSTRelationFilterOperatorArrayContains,
                "arrayContains queries don't make sense on document keys.");
    FSTReferenceValue *refValue = (FSTReferenceValue *)self.value;
    NSComparisonResult comparison = FSTDocumentKeyComparator(document.key, refValue.value);
    return [self matchesComparison:comparison];
  } else {
    return [self matchesValue:[document fieldForPath:self.field]];
  }
}

- (NSString *)canonicalID {
  // TODO(b/37283291): This should be collision robust and avoid relying on |description| methods.
  return [NSString stringWithFormat:@"%s%@%@", _field.CanonicalString().c_str(),
                                    FSTStringFromQueryRelationOperator(self.filterOperator),
                                    [self.value value]];
}

- (BOOL)isEqualToFilter:(FSTRelationFilter *)other {
  if (self.filterOperator != other.filterOperator) {
    return NO;
  }
  if (_field != other.field) {
    return NO;
  }
  if (![self.value isEqual:other.value]) {
    return NO;
  }
  return YES;
}

/** Returns YES if receiver is true with the given value as its LHS. */
- (BOOL)matchesValue:(FSTFieldValue *)other {
  if (self.filterOperator == FSTRelationFilterOperatorArrayContains) {
    if ([other isMemberOfClass:[FSTArrayValue class]]) {
      FSTArrayValue *arrayValue = (FSTArrayValue *)other;
      return [arrayValue.internalValue containsObject:self.value];
    } else {
      return false;
    }
  } else {
    // Only perform comparison queries on types with matching backend order (such as double and
    // int).
    return self.value.typeOrder == other.typeOrder &&
           [self matchesComparison:[other compare:self.value]];
  }
}

- (BOOL)matchesComparison:(NSComparisonResult)comparison {
  switch (self.filterOperator) {
    case FSTRelationFilterOperatorLessThan:
      return comparison == NSOrderedAscending;
    case FSTRelationFilterOperatorLessThanOrEqual:
      return comparison == NSOrderedAscending || comparison == NSOrderedSame;
    case FSTRelationFilterOperatorEqual:
      return comparison == NSOrderedSame;
    case FSTRelationFilterOperatorGreaterThanOrEqual:
      return comparison == NSOrderedDescending || comparison == NSOrderedSame;
    case FSTRelationFilterOperatorGreaterThan:
      return comparison == NSOrderedDescending;
    default:
      HARD_FAIL("Unknown operator: %s", self.filterOperator);
  }
}

@end

#pragma mark - FSTNullFilter

@interface FSTNullFilter () {
  FieldPath _field;
}
@end

@implementation FSTNullFilter
- (instancetype)initWithField:(FieldPath)field {
  if (self = [super init]) {
    _field = std::move(field);
  }
  return self;
}

- (BOOL)matchesDocument:(FSTDocument *)document {
  FSTFieldValue *fieldValue = [document fieldForPath:self.field];
  return fieldValue != nil && [fieldValue isEqual:[FSTNullValue nullValue]];
}

- (NSString *)canonicalID {
  return [NSString stringWithFormat:@"%s IS NULL", _field.CanonicalString().c_str()];
}

- (const firebase::firestore::model::FieldPath &)field {
  return _field;
}

- (NSString *)description {
  return [self canonicalID];
}

- (BOOL)isEqual:(id)other {
  if (other == self) return YES;
  if (![[other class] isEqual:[self class]]) return NO;

  return _field == ((FSTNullFilter *)other)->_field;
}

- (NSUInteger)hash {
  return util::Hash(_field);
}

@end

#pragma mark - FSTNanFilter

@interface FSTNanFilter () {
  FieldPath _field;
}
@end

@implementation FSTNanFilter

- (instancetype)initWithField:(FieldPath)field {
  if (self = [super init]) {
    _field = std::move(field);
  }
  return self;
}

- (BOOL)matchesDocument:(FSTDocument *)document {
  FSTFieldValue *fieldValue = [document fieldForPath:self.field];
  return fieldValue != nil && [fieldValue isEqual:[FSTDoubleValue nanValue]];
}

- (NSString *)canonicalID {
  return [NSString stringWithFormat:@"%s IS NaN", _field.CanonicalString().c_str()];
}

- (const firebase::firestore::model::FieldPath &)field {
  return _field;
}

- (NSString *)description {
  return [self canonicalID];
}

- (BOOL)isEqual:(id)other {
  if (other == self) return YES;
  if (![[other class] isEqual:[self class]]) return NO;

  return _field == ((FSTNanFilter *)other)->_field;
}

- (NSUInteger)hash {
  return util::Hash(_field);
}
@end

#pragma mark - FSTSortOrder

@interface FSTSortOrder () {
  /** The field to sort by. */
  firebase::firestore::model::FieldPath _field;
}

/** Creates a new sort order with the given field and direction. */
- (instancetype)initWithFieldPath:(FieldPath)fieldPath ascending:(BOOL)ascending;

- (NSString *)canonicalID;

@end

@implementation FSTSortOrder

#pragma mark - Constructor methods

+ (instancetype)sortOrderWithFieldPath:(FieldPath)fieldPath ascending:(BOOL)ascending {
  return [[FSTSortOrder alloc] initWithFieldPath:std::move(fieldPath) ascending:ascending];
}

- (instancetype)initWithFieldPath:(FieldPath)fieldPath ascending:(BOOL)ascending {
  self = [super init];
  if (self) {
    _field = std::move(fieldPath);
    _ascending = ascending;
  }
  return self;
}

- (const firebase::firestore::model::FieldPath &)field {
  return _field;
}

#pragma mark - Public methods

- (NSComparisonResult)compareDocument:(FSTDocument *)document1 toDocument:(FSTDocument *)document2 {
  NSComparisonResult result;
  if (_field == FieldPath::KeyFieldPath()) {
    result = FSTDocumentKeyComparator(document1.key, document2.key);
  } else {
    FSTFieldValue *value1 = [document1 fieldForPath:self.field];
    FSTFieldValue *value2 = [document2 fieldForPath:self.field];
    HARD_ASSERT(value1 != nil && value2 != nil,
                "Trying to compare documents on fields that don't exist.");
    result = [value1 compare:value2];
  }
  if (!self.isAscending) {
    result = ReverseOrder(result);
  }
  return result;
}

- (NSString *)canonicalID {
  return [NSString stringWithFormat:@"%s%@", _field.CanonicalString().c_str(),
                                    self.isAscending ? @"asc" : @"desc"];
}

- (BOOL)isEqualToSortOrder:(FSTSortOrder *)other {
  return _field == other->_field && self.isAscending == other.isAscending;
}

#pragma mark - NSObject methods

- (NSString *)description {
  return [NSString stringWithFormat:@"<FSTSortOrder: path:%s dir:%@>",
                                    _field.CanonicalString().c_str(),
                                    self.ascending ? @"asc" : @"desc"];
}

- (BOOL)isEqual:(NSObject *)other {
  if (self == other) {
    return YES;
  }
  if (![other isKindOfClass:[FSTSortOrder class]]) {
    return NO;
  }
  return [self isEqualToSortOrder:(FSTSortOrder *)other];
}

- (NSUInteger)hash {
  return [self.canonicalID hash];
}

- (instancetype)copyWithZone:(nullable NSZone *)zone {
  return self;
}

@end

#pragma mark - FSTBound

@implementation FSTBound

- (instancetype)initWithPosition:(NSArray<FSTFieldValue *> *)position isBefore:(BOOL)isBefore {
  if (self = [super init]) {
    _position = position;
    _before = isBefore;
  }
  return self;
}

+ (instancetype)boundWithPosition:(NSArray<FSTFieldValue *> *)position isBefore:(BOOL)isBefore {
  return [[FSTBound alloc] initWithPosition:position isBefore:isBefore];
}

- (NSString *)canonicalString {
  // TODO(b/29183165): Make this collision robust.
  NSMutableString *string = [NSMutableString string];
  if (self.isBefore) {
    [string appendString:@"b:"];
  } else {
    [string appendString:@"a:"];
  }
  for (FSTFieldValue *component in self.position) {
    [string appendFormat:@"%@", component];
  }
  return string;
}

- (BOOL)sortsBeforeDocument:(FSTDocument *)document
             usingSortOrder:(NSArray<FSTSortOrder *> *)sortOrder {
  HARD_ASSERT(self.position.count <= sortOrder.count,
              "FSTIndexPosition has more components than provided sort order.");
  __block NSComparisonResult result = NSOrderedSame;
  [self.position enumerateObjectsUsingBlock:^(FSTFieldValue *fieldValue, NSUInteger idx,
                                              BOOL *stop) {
    FSTSortOrder *sortOrderComponent = sortOrder[idx];
    NSComparisonResult comparison;
    if (sortOrderComponent.field == FieldPath::KeyFieldPath()) {
      HARD_ASSERT([fieldValue isKindOfClass:[FSTReferenceValue class]],
                  "FSTBound has a non-key value where the key path is being used %s", fieldValue);
      FSTReferenceValue *refValue = (FSTReferenceValue *)fieldValue;
      comparison = [refValue.value compare:document.key];
    } else {
      FSTFieldValue *docValue = [document fieldForPath:sortOrderComponent.field];
      HARD_ASSERT(docValue != nil,
                  "Field should exist since document matched the orderBy already.");
      comparison = [fieldValue compare:docValue];
    }

    if (!sortOrderComponent.isAscending) {
      comparison = ReverseOrder(comparison);
    }

    if (comparison != 0) {
      result = comparison;
      *stop = YES;
    }
  }];

  return self.isBefore ? result <= NSOrderedSame : result < NSOrderedSame;
}

#pragma mark - NSObject methods

- (NSString *)description {
  return [NSString stringWithFormat:@"<FSTBound: position:%@ before:%@>", self.position,
                                    self.isBefore ? @"YES" : @"NO"];
}

- (BOOL)isEqual:(NSObject *)other {
  if (self == other) {
    return YES;
  }
  if (![other isKindOfClass:[FSTBound class]]) {
    return NO;
  }

  FSTBound *otherBound = (FSTBound *)other;

  return [self.position isEqualToArray:otherBound.position] && self.isBefore == otherBound.isBefore;
}

- (NSUInteger)hash {
  return 31 * self.position.hash + (self.isBefore ? 0 : 1);
}

- (instancetype)copyWithZone:(nullable NSZone *)zone {
  return self;
}

@end

#pragma mark - FSTQuery

@interface FSTQuery () {
  // Cached value of the canonicalID property.
  NSString *_canonicalID;
  /** The base path of the query. */
  ResourcePath _path;
}

/**
 * Initializes the receiver with the given query constraints.
 *
 * @param path The base path of the query.
 * @param filters Filters specify which documents to include in the results.
 * @param sortOrders The fields and directions to sort the results.
 * @param limit If not NSNotFound, only this many results will be returned.
 */
- (instancetype)initWithPath:(ResourcePath)path
                    filterBy:(NSArray<id<FSTFilter>> *)filters
                     orderBy:(NSArray<FSTSortOrder *> *)sortOrders
                       limit:(NSInteger)limit
                     startAt:(nullable FSTBound *)startAtBound
                       endAt:(nullable FSTBound *)endAtBound NS_DESIGNATED_INITIALIZER;

/** A list of fields given to sort by. This does not include the implicit key sort at the end. */
@property(nonatomic, strong, readonly) NSArray<FSTSortOrder *> *explicitSortOrders;

/** The memoized list of sort orders */
@property(nonatomic, nullable, strong, readwrite) NSArray<FSTSortOrder *> *memoizedSortOrders;

@end

@implementation FSTQuery

#pragma mark - Constructors

+ (instancetype)queryWithPath:(ResourcePath)path {
  return [[FSTQuery alloc] initWithPath:std::move(path)
                               filterBy:@[]
                                orderBy:@[]
                                  limit:NSNotFound
                                startAt:nil
                                  endAt:nil];
}

- (instancetype)initWithPath:(ResourcePath)path
                    filterBy:(NSArray<id<FSTFilter>> *)filters
                     orderBy:(NSArray<FSTSortOrder *> *)sortOrders
                       limit:(NSInteger)limit
                     startAt:(nullable FSTBound *)startAtBound
                       endAt:(nullable FSTBound *)endAtBound {
  if (self = [super init]) {
    _path = std::move(path);
    _filters = filters;
    _explicitSortOrders = sortOrders;
    _limit = limit;
    _startAt = startAtBound;
    _endAt = endAtBound;
  }
  return self;
}

#pragma mark - NSObject methods

- (NSString *)description {
  return [NSString stringWithFormat:@"<FSTQuery: canonicalID:%@>", self.canonicalID];
}

- (BOOL)isEqual:(id)object {
  if (self == object) {
    return YES;
  }
  if (![object isKindOfClass:[FSTQuery class]]) {
    return NO;
  }
  return [self isEqualToQuery:(FSTQuery *)object];
}

- (NSUInteger)hash {
  return [self.canonicalID hash];
}

- (instancetype)copyWithZone:(nullable NSZone *)zone {
  return self;
}

#pragma mark - Public methods

- (NSArray *)sortOrders {
  if (self.memoizedSortOrders == nil) {
    const FieldPath *inequalityField = [self inequalityFilterField];
    const FieldPath *firstSortOrderField = [self firstSortOrderField];
    if (inequalityField && !firstSortOrderField) {
      // In order to implicitly add key ordering, we must also add the inequality filter field for
      // it to be a valid query. Note that the default inequality field and key ordering is
      // ascending.
      if (inequalityField->IsKeyFieldPath()) {
        self.memoizedSortOrders =
            @[ [FSTSortOrder sortOrderWithFieldPath:FieldPath::KeyFieldPath() ascending:YES] ];
      } else {
        self.memoizedSortOrders = @[
          [FSTSortOrder sortOrderWithFieldPath:*inequalityField ascending:YES],
          [FSTSortOrder sortOrderWithFieldPath:FieldPath::KeyFieldPath() ascending:YES]
        ];
      }
    } else {
      HARD_ASSERT(!inequalityField || *inequalityField == *firstSortOrderField,
                  "First orderBy %s should match inequality field %s.",
                  firstSortOrderField->CanonicalString(), inequalityField->CanonicalString());

      __block BOOL foundKeyOrder = NO;

      NSMutableArray *result = [NSMutableArray array];
      for (FSTSortOrder *sortOrder in self.explicitSortOrders) {
        [result addObject:sortOrder];
        if (sortOrder.field == FieldPath::KeyFieldPath()) {
          foundKeyOrder = YES;
        }
      }

      if (!foundKeyOrder) {
        // The direction of the implicit key ordering always matches the direction of the last
        // explicit sort order
        BOOL lastIsAscending =
            self.explicitSortOrders.count > 0 ? self.explicitSortOrders.lastObject.ascending : YES;
        [result addObject:[FSTSortOrder sortOrderWithFieldPath:FieldPath::KeyFieldPath()
                                                     ascending:lastIsAscending]];
      }

      self.memoizedSortOrders = result;
    }
  }
  return self.memoizedSortOrders;
}

- (instancetype)queryByAddingFilter:(id<FSTFilter>)filter {
  HARD_ASSERT(!DocumentKey::IsDocumentKey(_path), "No filtering allowed for document query");

  const FieldPath *newInequalityField = nullptr;
  if ([filter isKindOfClass:[FSTRelationFilter class]] &&
      [((FSTRelationFilter *)filter)isInequality]) {
    newInequalityField = &filter.field;
  }
  const FieldPath *queryInequalityField = [self inequalityFilterField];
  HARD_ASSERT(
      !queryInequalityField || !newInequalityField || *queryInequalityField == *newInequalityField,
      "Query must only have one inequality field.");

  return [[FSTQuery alloc] initWithPath:self.path
                               filterBy:[self.filters arrayByAddingObject:filter]
                                orderBy:self.explicitSortOrders
                                  limit:self.limit
                                startAt:self.startAt
                                  endAt:self.endAt];
}

- (instancetype)queryByAddingSortOrder:(FSTSortOrder *)sortOrder {
  HARD_ASSERT(!DocumentKey::IsDocumentKey(_path), "No ordering is allowed for a document query.");

  // TODO(klimt): Validate that the same key isn't added twice.
  return [[FSTQuery alloc] initWithPath:self.path
                               filterBy:self.filters
                                orderBy:[self.explicitSortOrders arrayByAddingObject:sortOrder]
                                  limit:self.limit
                                startAt:self.startAt
                                  endAt:self.endAt];
}

- (instancetype)queryBySettingLimit:(NSInteger)limit {
  return [[FSTQuery alloc] initWithPath:self.path
                               filterBy:self.filters
                                orderBy:self.explicitSortOrders
                                  limit:limit
                                startAt:self.startAt
                                  endAt:self.endAt];
}

- (instancetype)queryByAddingStartAt:(FSTBound *)bound {
  return [[FSTQuery alloc] initWithPath:self.path
                               filterBy:self.filters
                                orderBy:self.explicitSortOrders
                                  limit:self.limit
                                startAt:bound
                                  endAt:self.endAt];
}

- (instancetype)queryByAddingEndAt:(FSTBound *)bound {
  return [[FSTQuery alloc] initWithPath:self.path
                               filterBy:self.filters
                                orderBy:self.explicitSortOrders
                                  limit:self.limit
                                startAt:self.startAt
                                  endAt:bound];
}

- (BOOL)isDocumentQuery {
  return DocumentKey::IsDocumentKey(_path) && self.filters.count == 0;
}

- (BOOL)matchesDocument:(FSTDocument *)document {
  return [self pathMatchesDocument:document] && [self orderByMatchesDocument:document] &&
         [self filtersMatchDocument:document] && [self boundsMatchDocument:document];
}

- (NSComparator)comparator {
  return ^NSComparisonResult(id document1, id document2) {
    BOOL didCompareOnKeyField = NO;
    for (FSTSortOrder *orderBy in self.sortOrders) {
      NSComparisonResult comp = [orderBy compareDocument:document1 toDocument:document2];
      if (comp != NSOrderedSame) {
        return comp;
      }
      didCompareOnKeyField = didCompareOnKeyField || orderBy.field == FieldPath::KeyFieldPath();
    }
    HARD_ASSERT(didCompareOnKeyField, "sortOrder of query did not include key ordering");
    return NSOrderedSame;
  };
}

- (const FieldPath *)inequalityFilterField {
  for (id<FSTFilter> filter in self.filters) {
    if ([filter isKindOfClass:[FSTRelationFilter class]] &&
        ((FSTRelationFilter *)filter).isInequality) {
      return &filter.field;
    }
  }
  return nullptr;
}

- (BOOL)hasArrayContainsFilter {
  for (id<FSTFilter> filter in self.filters) {
    if ([filter isKindOfClass:[FSTRelationFilter class]] &&
        ((FSTRelationFilter *)filter).filterOperator == FSTRelationFilterOperatorArrayContains) {
      return YES;
    }
  }
  return NO;
}

- (const FieldPath *)firstSortOrderField {
  if (self.explicitSortOrders.count > 0) {
    return &self.explicitSortOrders.firstObject.field;
  }
  return nullptr;
}

/** The base path of the query. */
- (const firebase::firestore::model::ResourcePath &)path {
  return _path;
}

#pragma mark - Private properties

- (NSString *)canonicalID {
  if (_canonicalID) {
    return _canonicalID;
  }

  NSMutableString *canonicalID = [NSMutableString string];
  [canonicalID appendFormat:@"%s", _path.CanonicalString().c_str()];

  // Add filters.
  [canonicalID appendString:@"|f:"];
  for (id<FSTFilter> predicate in self.filters) {
    [canonicalID appendFormat:@"%@", [predicate canonicalID]];
  }

  // Add order by.
  [canonicalID appendString:@"|ob:"];
  for (FSTSortOrder *orderBy in self.sortOrders) {
    [canonicalID appendString:orderBy.canonicalID];
  }

  // Add limit.
  if (self.limit != NSNotFound) {
    [canonicalID appendFormat:@"|l:%ld", (long)self.limit];
  }

  if (self.startAt) {
    [canonicalID appendFormat:@"|lb:%@", self.startAt.canonicalString];
  }

  if (self.endAt) {
    [canonicalID appendFormat:@"|ub:%@", self.endAt.canonicalString];
  }

  _canonicalID = canonicalID;
  return canonicalID;
}

#pragma mark - Private methods

- (BOOL)isEqualToQuery:(FSTQuery *)other {
  return self.path == other.path && self.limit == other.limit &&
         [self.filters isEqual:other.filters] && [self.sortOrders isEqual:other.sortOrders] &&
         (self.startAt == other.startAt || [self.startAt isEqual:other.startAt]) &&
         (self.endAt == other.endAt || [self.endAt isEqual:other.endAt]);
}

/* Returns YES if the document matches the path for the receiver. */
- (BOOL)pathMatchesDocument:(FSTDocument *)document {
  const ResourcePath &documentPath = document.key.path();
  if (DocumentKey::IsDocumentKey(_path)) {
    // Exact match for document queries.
    return self.path == documentPath;
  } else {
    // Shallow ancestor queries by default.
    return self.path.IsPrefixOf(documentPath) && _path.size() == documentPath.size() - 1;
  }
}

/**
 * A document must have a value for every ordering clause in order to show up in the results.
 */
- (BOOL)orderByMatchesDocument:(FSTDocument *)document {
  for (FSTSortOrder *orderBy in self.explicitSortOrders) {
    const FieldPath &fieldPath = orderBy.field;
    // order by key always matches
    if (fieldPath != FieldPath::KeyFieldPath() && [document fieldForPath:fieldPath] == nil) {
      return NO;
    }
  }
  return YES;
}

/** Returns YES if the document matches all of the filters in the receiver. */
- (BOOL)filtersMatchDocument:(FSTDocument *)document {
  for (id<FSTFilter> filter in self.filters) {
    if (![filter matchesDocument:document]) {
      return NO;
    }
  }
  return YES;
}

- (BOOL)boundsMatchDocument:(FSTDocument *)document {
  if (self.startAt && ![self.startAt sortsBeforeDocument:document usingSortOrder:self.sortOrders]) {
    return NO;
  }
  if (self.endAt && [self.endAt sortsBeforeDocument:document usingSortOrder:self.sortOrders]) {
    return NO;
  }
  return YES;
}

@end

NS_ASSUME_NONNULL_END