-
-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathQuery.swift
1706 lines (1538 loc) · 69.8 KB
/
Query.swift
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
//
// Query.swift
// Parse
//
// Created by Florent Vilmart on 17-07-23.
// Copyright © 2020 Parse Community. All rights reserved.
//
import Foundation
/**
All available query constraints.
*/
public struct QueryConstraint: Encodable, Equatable {
enum Comparator: String, CodingKey, Encodable {
case lessThan = "$lt"
case lessThanOrEqualTo = "$lte"
case greaterThan = "$gt"
case greaterThanOrEqualTo = "$gte"
case notEqualTo = "$ne"
case containedIn = "$in"
case notContainedIn = "$nin"
case containedBy = "$containedBy"
case exists = "$exists"
case select = "$select"
case dontSelect = "$dontSelect"
case all = "$all"
case regex = "$regex"
case inQuery = "$inQuery"
case notInQuery = "$notInQuery"
case nearSphere = "$nearSphere"
case or = "$or" //swiftlint:disable:this identifier_name
case and = "$and"
case nor = "$nor"
case relatedTo = "$relatedTo"
case within = "$within"
case geoWithin = "$geoWithin"
case geoIntersects = "$geoIntersects"
case maxDistance = "$maxDistance"
case centerSphere = "$centerSphere"
case box = "$box"
case polygon = "$polygon"
case point = "$point"
case text = "$text"
case search = "$search"
case term = "$term"
case regexOptions = "$options"
case object = "object"
case relativeTime = "$relativeTime"
}
var key: String
var value: Encodable
var comparator: Comparator?
public func encode(to encoder: Encoder) throws {
if let value = value as? Date {
// Parse uses special case for date
try value.parseRepresentation.encode(to: encoder)
} else {
try value.encode(to: encoder)
}
}
public static func == (lhs: QueryConstraint, rhs: QueryConstraint) -> Bool {
guard lhs.key == rhs.key,
lhs.comparator == rhs.comparator,
AnyEncodable(lhs.value) == AnyEncodable(rhs.value) else {
return false
}
return true
}
}
/**
Add a constraint that requires that a key is greater than a value.
- parameter key: The key that the value is stored in.
- parameter value: The value to compare.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func > <T>(key: String, value: T) -> QueryConstraint where T: Encodable {
QueryConstraint(key: key, value: value, comparator: .greaterThan)
}
/**
Add a constraint that requires that a key is greater than or equal to a value.
- parameter key: The key that the value is stored in.
- parameter value: The value to compare.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func >= <T>(key: String, value: T) -> QueryConstraint where T: Encodable {
QueryConstraint(key: key, value: value, comparator: .greaterThanOrEqualTo)
}
/**
Add a constraint that requires that a key is less than a value.
- parameter key: The key that the value is stored in.
- parameter value: The value to compare.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func < <T>(key: String, value: T) -> QueryConstraint where T: Encodable {
QueryConstraint(key: key, value: value, comparator: .lessThan)
}
/**
Add a constraint that requires that a key is less than or equal to a value.
- parameter key: The key that the value is stored in.
- parameter value: The value to compare.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func <= <T>(key: String, value: T) -> QueryConstraint where T: Encodable {
QueryConstraint(key: key, value: value, comparator: .lessThanOrEqualTo)
}
/**
Add a constraint that requires that a key is equal to a value.
- parameter key: The key that the value is stored in.
- parameter value: The value to compare.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func == <T>(key: String, value: T) -> QueryConstraint where T: Encodable {
QueryConstraint(key: key, value: value)
}
/**
Add a constraint that requires that a key is equal to a `ParseObject`.
- parameter key: The key that the value is stored in.
- parameter value: The `ParseObject` to compare.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func == <T>(key: String, value: T) throws -> QueryConstraint where T: ParseObject {
let constraint: QueryConstraint!
do {
constraint = try QueryConstraint(key: key, value: value.toPointer())
} catch {
guard let parseError = error as? ParseError else {
throw ParseError(code: .unknownError,
message: error.localizedDescription)
}
throw parseError
}
return constraint
}
/**
Add a constraint that requires that a key is not equal to a value.
- parameter key: The key that the value is stored in.
- parameter value: The value to compare.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func != <T>(key: String, value: T) -> QueryConstraint where T: Encodable {
QueryConstraint(key: key, value: value, comparator: .notEqualTo)
}
internal struct InQuery<T>: Encodable where T: ParseObject {
let query: Query<T>
var className: String {
return T.className
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(className, forKey: .className)
try container.encode(query.where, forKey: .where)
}
enum CodingKeys: String, CodingKey {
case `where`, className
}
}
internal struct OrAndQuery<T>: Encodable where T: ParseObject {
let query: Query<T>
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(query.where)
}
enum CodingKeys: String, CodingKey {
case `where`
}
}
internal struct QuerySelect<T>: Encodable where T: ParseObject {
let query: InQuery<T>
let key: String
}
/**
Returns a `Query` that is the `or` of the passed in queries.
- parameter queries: The list of queries to `or` together.
- returns: An instance of `QueryConstraint`'s that are the `or` of the passed in queries.
*/
public func or <T>(queries: [Query<T>]) -> QueryConstraint where T: Encodable {
let orQueries = queries.map { OrAndQuery(query: $0) }
return QueryConstraint(key: QueryConstraint.Comparator.or.rawValue, value: orQueries)
}
/**
Returns a `Query` that is the `nor` of the passed in queries.
- parameter queries: The list of queries to `nor` together.
- returns: An instance of `QueryConstraint`'s that are the `nor` of the passed in queries.
*/
public func nor <T>(queries: [Query<T>]) -> QueryConstraint where T: Encodable {
let orQueries = queries.map { OrAndQuery(query: $0) }
return QueryConstraint(key: QueryConstraint.Comparator.nor.rawValue, value: orQueries)
}
/**
Constructs a Query that is the `and` of the passed in queries. For
example:
~~~
var compoundQueryConstraints = and(query1, query2, query3)
~~~
will create a compoundQuery that is an and of the query1, query2, and
query3.
- parameter queries: The list of queries to `and` together.
- returns: An instance of `QueryConstraint`'s that are the `and` of the passed in queries.
*/
public func and <T>(queries: [Query<T>]) -> QueryConstraint where T: Encodable {
let andQueries = queries.map { OrAndQuery(query: $0) }
return QueryConstraint(key: QueryConstraint.Comparator.and.rawValue, value: andQueries)
}
/**
Add a constraint that requires that a key's value matches a `Query` constraint.
- warning: This only works where the key's values are `ParseObject`s or arrays of `ParseObject`s.
- parameter key: The key that the value is stored in.
- parameter query: The query the value should match.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func == <T>(key: String, value: Query<T>) -> QueryConstraint {
QueryConstraint(key: key, value: InQuery(query: value), comparator: .inQuery)
}
/**
Add a constraint that requires that a key's value do not match a `Query` constraint.
- warning: This only works where the key's values are `ParseObject`s or arrays of `ParseObject`s.
- parameter key: The key that the value is stored in.
- parameter query: The query the value should not match.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func != <T>(key: String, query: Query<T>) -> QueryConstraint {
QueryConstraint(key: key, value: InQuery(query: query), comparator: .notInQuery)
}
/**
Adds a constraint that requires that a key's value matches a value in another key
in objects returned by a sub query.
- parameter key: The key that the value is stored.
- parameter queryKey: The key in objects in the returned by the sub query whose value should match.
- parameter query: The query to run.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func matchesKeyInQuery <T>(key: String, queryKey: String, query: Query<T>) -> QueryConstraint {
let select = QuerySelect(query: InQuery(query: query), key: queryKey)
return QueryConstraint(key: key, value: select, comparator: .select)
}
/**
Adds a constraint that requires that a key's value *not* match a value in another key
in objects returned by a sub query.
- parameter key: The key that the value is stored.
- parameter queryKey: The key in objects returned by the sub query whose value should match.
- parameter query: The query to run.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func doesNotMatchKeyInQuery <T>(key: String, queryKey: String, query: Query<T>) -> QueryConstraint {
let select = QuerySelect(query: InQuery(query: query), key: queryKey)
return QueryConstraint(key: key, value: select, comparator: .dontSelect)
}
/**
Add a constraint to the query that requires a particular key's object
to be contained in the provided array.
- parameter key: The key to be constrained.
- parameter array: The possible values for the key's object.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func containedIn <T>(key: String, array: [T]) -> QueryConstraint where T: Encodable {
QueryConstraint(key: key, value: array, comparator: .containedIn)
}
/**
Add a constraint to the query that requires a particular key's object
not be contained in the provided array.
- parameter key: The key to be constrained.
- parameter array: The list of values the key's object should not be.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func notContainedIn <T>(key: String, array: [T]) -> QueryConstraint where T: Encodable {
QueryConstraint(key: key, value: array, comparator: .notContainedIn)
}
/**
Add a constraint to the query that requires a particular key's array
contains every element of the provided array.
- parameter key: The key to be constrained.
- parameter array: The possible values for the key's object.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func containsAll <T>(key: String, array: [T]) -> QueryConstraint where T: Encodable {
QueryConstraint(key: key, value: array, comparator: .all)
}
/**
Add a constraint to the query that requires a particular key's object
to be contained by the provided array. Get objects where all array elements match.
- parameter key: The key to be constrained.
- parameter array: The possible values for the key's object.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func containedBy <T>(key: String, array: [T]) -> QueryConstraint where T: Encodable {
QueryConstraint(key: key, value: array, comparator: .containedBy)
}
/**
Add a constraint to the query that requires a particular key's time is related to a specified time. For example:
~~~
let queryRelative = GameScore.query(relative("createdAt" < "12 days ago"))
~~~
will create a relative query where `createdAt` is less than 12 days ago.
- parameter constraint: The key to be constrained. Should be a Date field. The value is a
reference time, e.g. "12 days ago". Currently only comparators supported are: <, <=, >=, and >=.
- returns: The same instance of `QueryConstraint` as the receiver.
- warning: This only works with Parse Servers using mongoDB.
*/
public func relative(_ constraint: QueryConstraint) -> QueryConstraint {
QueryConstraint(key: constraint.key,
value: [QueryConstraint.Comparator.relativeTime.rawValue: AnyEncodable(constraint.value)],
comparator: constraint.comparator)
}
/**
Add a constraint to the query that requires a particular key's coordinates (specified via `ParseGeoPoint`)
be near a reference point. Distance is calculated based on angular distance on a sphere. Results will be sorted
by distance from reference point.
- parameter key: The key to be constrained.
- parameter geoPoint: The reference point represented as a `ParseGeoPoint`.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func near(key: String, geoPoint: ParseGeoPoint) -> QueryConstraint {
QueryConstraint(key: key, value: geoPoint, comparator: .nearSphere)
}
/**
Add a constraint to the query that requires a particular key's coordinates (specified via `ParseGeoPoint`) be near
a reference point and within the maximum distance specified (in radians). Distance is calculated based on
angular distance on a sphere. Results will be sorted by distance (nearest to farthest) from the reference point.
- parameter key: The key to be constrained.
- parameter geoPoint: The reference point as a `ParseGeoPoint`.
- parameter distance: Maximum distance in radians.
- parameter sorted: `true` if results should be sorted by distance ascending, `false` is no sorting is required.
Defaults to true.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func withinRadians(key: String,
geoPoint: ParseGeoPoint,
distance: Double,
sorted: Bool = true) -> [QueryConstraint] {
if sorted {
var constraints = [QueryConstraint(key: key, value: geoPoint, comparator: .nearSphere)]
constraints.append(.init(key: key, value: distance, comparator: .maxDistance))
return constraints
} else {
var constraints = [QueryConstraint(key: key, value: geoPoint, comparator: .centerSphere)]
constraints.append(.init(key: key, value: distance, comparator: .geoWithin))
return constraints
}
}
/**
Add a constraint to the query that requires a particular key's coordinates (specified via `ParseGeoPoint`)
be near a reference point and within the maximum distance specified (in miles). Distance is calculated based
on a spherical coordinate system. Results will be sorted by distance (nearest to farthest) from the reference point.
- parameter key: The key to be constrained.
- parameter geoPoint: The reference point represented as a `ParseGeoPoint`.
- parameter distance: Maximum distance in miles.
- parameter sorted: `true` if results should be sorted by distance ascending, `false` is no sorting is required.
Defaults to true.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func withinMiles(key: String,
geoPoint: ParseGeoPoint,
distance: Double,
sorted: Bool = true) -> [QueryConstraint] {
return withinRadians(key: key, geoPoint: geoPoint, distance: (distance / ParseGeoPoint.earthRadiusMiles))
}
/**
Add a constraint to the query that requires a particular key's coordinates (specified via `ParseGeoPoint`)
be near a reference point and within the maximum distance specified (in kilometers). Distance is calculated based
on a spherical coordinate system. Results will be sorted by distance (nearest to farthest) from the reference point.
- parameter key: The key to be constrained.
- parameter geoPoint: The reference point represented as a `ParseGeoPoint`.
- parameter distance: Maximum distance in kilometers.
- parameter sorted: `true` if results should be sorted by distance ascending, `false` is no sorting is required.
Defaults to true.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func withinKilometers(key: String,
geoPoint: ParseGeoPoint,
distance: Double,
sorted: Bool = true) -> [QueryConstraint] {
return withinRadians(key: key, geoPoint: geoPoint, distance: (distance / ParseGeoPoint.earthRadiusKilometers))
}
/**
Add a constraint to the query that requires a particular key's coordinates (specified via `ParseGeoPoint`) be
contained within a given rectangular geographic bounding box.
- parameter key: The key to be constrained.
- parameter fromSouthWest: The lower-left inclusive corner of the box.
- parameter toNortheast: The upper-right inclusive corner of the box.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func withinGeoBox(key: String, fromSouthWest southwest: ParseGeoPoint,
toNortheast northeast: ParseGeoPoint) -> QueryConstraint {
let array = [southwest, northeast]
let dictionary = [QueryConstraint.Comparator.box.rawValue: array]
return .init(key: key, value: dictionary, comparator: .within)
}
/**
Add a constraint to the query that requires a particular key's
coordinates be contained within and on the bounds of a given polygon
Supports closed and open (last point is connected to first) paths.
Polygon must have at least 3 points.
- parameter key: The key to be constrained.
- parameter points: The polygon points as an Array of `ParseGeoPoint`'s.
- warning: Requires Parse Server 2.5.0+.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func withinPolygon(key: String, points: [ParseGeoPoint]) -> QueryConstraint {
let dictionary = [QueryConstraint.Comparator.polygon.rawValue: points]
return .init(key: key, value: dictionary, comparator: .geoWithin)
}
/**
Add a constraint to the query that requires a particular key's
coordinates that contains a `ParseGeoPoint`.
- parameter key: The key to be constrained.
- parameter point: The point the polygon contains `ParseGeoPoint`.
- warning: Requires Parse Server 2.6.0+.
- returns: The same instance of `QueryConstraint` as the receiver.
*/
public func polygonContains(key: String, point: ParseGeoPoint) -> QueryConstraint {
let dictionary = [QueryConstraint.Comparator.point.rawValue: point]
return .init(key: key, value: dictionary, comparator: .geoIntersects)
}
/**
Add a constraint for finding string values that contain a provided
string using Full Text Search.
- parameter key: The key to be constrained.
- parameter text: The substring that the value must contain.
- returns: The same instance of `Query` as the receiver.
*/
public func matchesText(key: String, text: String) -> QueryConstraint {
let dictionary = [QueryConstraint.Comparator.search.rawValue: [QueryConstraint.Comparator.term.rawValue: text]]
return .init(key: key, value: dictionary, comparator: .text)
}
/**
Add a regular expression constraint for finding string values that match the provided regular expression.
- warning: This may be slow for large datasets.
- parameter key: The key that the string to match is stored in.
- parameter regex: The regular expression pattern to match.
- parameter modifiers: Any of the following supported PCRE modifiers (defaults to nil):
- `i` - Case insensitive search
- `m` - Search across multiple lines of input
- returns: The same instance of `Query` as the receiver.
*/
public func matchesRegex(key: String, regex: String, modifiers: String? = nil) -> QueryConstraint {
if let modifiers = modifiers {
let dictionary = [
QueryConstraint.Comparator.regex.rawValue: regex,
QueryConstraint.Comparator.regexOptions.rawValue: modifiers
]
return .init(key: key, value: dictionary)
} else {
return .init(key: key, value: regex, comparator: .regex)
}
}
private func regexStringForString(_ inputString: String) -> String {
let escapedString = inputString.replacingOccurrences(of: "\\E", with: "\\E\\\\E\\Q")
return "\\Q\(escapedString)\\E"
}
/**
Add a constraint for finding string values that contain a provided substring.
- warning: This will be slow for large datasets.
- parameter key: The key that the string to match is stored in.
- parameter substring: The substring that the value must contain.
- parameter modifiers: Any of the following supported PCRE modifiers (defaults to nil):
- `i` - Case insensitive search
- `m` - Search across multiple lines of input
- returns: The same instance of `Query` as the receiver.
*/
public func containsString(key: String, substring: String, modifiers: String? = nil) -> QueryConstraint {
let regex = regexStringForString(substring)
return matchesRegex(key: key, regex: regex, modifiers: modifiers)
}
/**
Add a constraint for finding string values that start with a provided prefix.
This will use smart indexing, so it will be fast for large datasets.
- parameter key: The key that the string to match is stored in.
- parameter prefix: The substring that the value must start with.
- parameter modifiers: Any of the following supported PCRE modifiers (defaults to nil):
- `i` - Case insensitive search
- `m` - Search across multiple lines of input
- returns: The same instance of `Query` as the receiver.
*/
public func hasPrefix(key: String, prefix: String, modifiers: String? = nil) -> QueryConstraint {
let regex = "^\(regexStringForString(prefix))"
return matchesRegex(key: key, regex: regex, modifiers: modifiers)
}
/**
Add a constraint for finding string values that end with a provided suffix.
- warning: This will be slow for large datasets.
- parameter key: The key that the string to match is stored in.
- parameter suffix: The substring that the value must end with.
- parameter modifiers: Any of the following supported PCRE modifiers (defaults to nil):
- `i` - Case insensitive search
- `m` - Search across multiple lines of input
- returns: The same instance of `Query` as the receiver.
*/
public func hasSuffix(key: String, suffix: String, modifiers: String? = nil) -> QueryConstraint {
let regex = "\(regexStringForString(suffix))$"
return matchesRegex(key: key, regex: regex, modifiers: modifiers)
}
/**
Add a constraint that requires a particular key exists.
- parameter key: The key that should exist.
- returns: The same instance of `Query` as the receiver.
*/
public func exists(key: String) -> QueryConstraint {
return .init(key: key, value: true, comparator: .exists)
}
/**
Add a constraint that requires a key not exist.
- parameter key: The key that should not exist.
- returns: The same instance of `Query` as the receiver.
*/
public func doesNotExist(key: String) -> QueryConstraint {
return .init(key: key, value: false, comparator: .exists)
}
internal struct RelatedCondition <T>: Encodable where T: ParseObject {
let object: Pointer<T>
let key: String
}
/**
Add a constraint that requires a key is related.
- parameter key: The key that should be related.
- parameter object: The object that should be related.
- returns: The same instance of `Query` as the receiver.
*/
public func related <T>(key: String, object: Pointer<T>) -> QueryConstraint where T: ParseObject {
let condition = RelatedCondition(object: object, key: key)
return .init(key: QueryConstraint.Comparator.relatedTo.rawValue, value: condition)
}
internal struct QueryWhere: Encodable, Equatable {
var constraints = [String: [QueryConstraint]]()
mutating func add(_ constraint: QueryConstraint) {
var existing = constraints[constraint.key] ?? []
existing.append(constraint)
constraints[constraint.key] = existing
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: RawCodingKey.self)
try constraints.forEach { (key, value) in
try value.forEach { (constraint) in
if constraint.comparator != nil {
var nestedContainer = container.nestedContainer(keyedBy: QueryConstraint.Comparator.self,
forKey: .key(key))
try constraint.encode(to: nestedContainer.superEncoder(forKey: constraint.comparator!))
} else {
try container.encode(constraint, forKey: .key(key))
}
}
}
}
}
struct AggregateBody<T>: Encodable where T: ParseObject {
let pipeline: [[String: AnyEncodable]]?
let hint: AnyEncodable?
let explain: Bool?
let includeReadPreference: String?
init(query: Query<T>) {
pipeline = query.pipeline
hint = query.hint
explain = query.explain
includeReadPreference = query.includeReadPreference
}
}
struct DistinctBody<T>: Encodable where T: ParseObject {
let hint: AnyEncodable?
let explain: Bool?
let includeReadPreference: String?
let distinct: String?
init(query: Query<T>) {
distinct = query.distinct
hint = query.hint
explain = query.explain
includeReadPreference = query.includeReadPreference
}
}
// MARK: Query
/**
The `Query` class defines a query that is used to query for `ParseObject`s.
*/
public struct Query<T>: Encodable, Equatable where T: ParseObject {
// interpolate as GET
private let method: String = "GET"
internal var limit: Int = 100
internal var skip: Int = 0
internal var keys: Set<String>?
internal var include: Set<String>?
internal var order: [Order]?
internal var isCount: Bool?
internal var explain: Bool?
internal var hint: AnyEncodable?
internal var `where` = QueryWhere()
internal var excludeKeys: Set<String>?
internal var readPreference: String?
internal var includeReadPreference: String?
internal var subqueryReadPreference: String?
internal var distinct: String?
internal var pipeline: [[String: AnyEncodable]]?
internal var fields: Set<String>?
/**
An enum that determines the order to sort the results based on a given key.
- parameter key: The key to order by.
*/
public enum Order: Encodable, Equatable {
/// Sort in ascending order based on `key`.
case ascending(String)
/// Sort in descending order based on `key`.
case descending(String)
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .ascending(let value):
try container.encode(value)
case .descending(let value):
try container.encode("-\(value)")
}
}
}
/**
Create an instance with a variadic amount constraints.
- parameter constraints: A variadic amount of zero or more `QueryConstraint`'s.
*/
public init(_ constraints: QueryConstraint...) {
self.init(constraints)
}
/**
Create an instance with an array of constraints.
- parameter constraints: An array of `QueryConstraint`'s.
*/
public init(_ constraints: [QueryConstraint]) {
constraints.forEach({ self.where.add($0) })
}
public static func == (lhs: Query<T>, rhs: Query<T>) -> Bool {
guard lhs.limit == rhs.limit,
lhs.skip == rhs.skip,
lhs.keys == rhs.keys,
lhs.include == rhs.include,
lhs.order == rhs.order,
lhs.isCount == rhs.isCount,
lhs.explain == rhs.explain,
lhs.hint == rhs.hint,
lhs.`where` == rhs.`where`,
lhs.excludeKeys == rhs.excludeKeys,
lhs.readPreference == rhs.readPreference,
lhs.includeReadPreference == rhs.includeReadPreference,
lhs.subqueryReadPreference == rhs.subqueryReadPreference,
lhs.distinct == rhs.distinct,
lhs.pipeline == rhs.pipeline,
lhs.fields == rhs.fields else {
return false
}
return true
}
/**
Add any amount of variadic constraints.
- parameter constraints: A variadic amount of zero or more `QueryConstraint`'s.
*/
public func `where`(_ constraints: QueryConstraint...) -> Query<T> {
var mutableQuery = self
constraints.forEach({ mutableQuery.where.add($0) })
return mutableQuery
}
/**
A limit on the number of objects to return. The default limit is `100`, with a
maximum of 1000 results being returned at a time.
- parameter value: `n` number of results to limit to.
- note: If you are calling `find` with `limit = 1`, you may find it easier to use `first` instead.
*/
public func limit(_ value: Int) -> Query<T> {
var mutableQuery = self
mutableQuery.limit = value
return mutableQuery
}
/**
The number of objects to skip before returning any.
This is useful for pagination. Default is to skip zero results.
- parameter value: `n` number of results to skip.
*/
public func skip(_ value: Int) -> Query<T> {
var mutableQuery = self
mutableQuery.skip = value
return mutableQuery
}
/**
Adds a hint to force index selection.
- parameter value: String or Object of index that should be used when executing query.
*/
public func hint<U: Encodable>(_ value: U) -> Query<T> {
var mutableQuery = self
mutableQuery.hint = AnyEncodable(value)
return mutableQuery
}
/**
Changes the read preference that the backend will use when performing the query to the database.
- parameter readPreference: The read preference for the main query.
- parameter includeReadPreference: The read preference for the queries to include pointers.
- parameter subqueryReadPreference: The read preference for the sub queries.
*/
public func readPreference(_ readPreference: String?,
includeReadPreference: String? = nil,
subqueryReadPreference: String? = nil) -> Query<T> {
var mutableQuery = self
mutableQuery.readPreference = readPreference
mutableQuery.includeReadPreference = includeReadPreference
mutableQuery.subqueryReadPreference = subqueryReadPreference
return mutableQuery
}
/**
Make the query include `ParseObject`s that have a reference stored at the provided keys.
If this is called multiple times, then all of the keys specified in each of the calls will be included.
- parameter keys: A variadic list of keys to load child `ParseObject`s for.
*/
public func include(_ keys: String...) -> Query<T> {
var mutableQuery = self
if mutableQuery.include != nil {
mutableQuery.include = mutableQuery.include?.union(keys)
} else {
mutableQuery.include = Set(keys)
}
return mutableQuery
}
/**
Make the query include `ParseObject`s that have a reference stored at the provided keys.
If this is called multiple times, then all of the keys specified in each of the calls will be included.
- parameter keys: An array of keys to load child `ParseObject`s for.
*/
public func include(_ keys: [String]) -> Query<T> {
var mutableQuery = self
if mutableQuery.include != nil {
mutableQuery.include = mutableQuery.include?.union(keys)
} else {
mutableQuery.include = Set(keys)
}
return mutableQuery
}
/**
Includes all nested `ParseObject`s one level deep.
- warning: Requires Parse Server 3.0.0+.
*/
public func includeAll() -> Query<T> {
var mutableQuery = self
mutableQuery.include = ["*"]
return mutableQuery
}
/**
Exclude specific keys for a `ParseObject`.
If this is called multiple times, then all of the keys specified in each of the calls will be excluded.
- parameter keys: A variadic list of keys include in the result.
- warning: Requires Parse Server > 4.5.0.
*/
public func exclude(_ keys: String...) -> Query<T> {
var mutableQuery = self
if mutableQuery.excludeKeys != nil {
mutableQuery.excludeKeys = mutableQuery.excludeKeys?.union(keys)
} else {
mutableQuery.excludeKeys = Set(keys)
}
return mutableQuery
}
/**
Exclude specific keys for a `ParseObject`.
If this is called multiple times, then all of the keys specified in each of the calls will be excluded.
- parameter keys: An array of keys to exclude in the result.
- warning: Requires Parse Server > 4.5.0.
*/
public func exclude(_ keys: [String]) -> Query<T> {
var mutableQuery = self
if mutableQuery.excludeKeys != nil {
mutableQuery.excludeKeys = mutableQuery.excludeKeys?.union(keys)
} else {
mutableQuery.excludeKeys = Set(keys)
}
return mutableQuery
}
/**
Make the query restrict the fields of the returned `ParseObject`s to include only the provided keys.
If this is called multiple times, then all of the keys specified in each of the calls will be included.
- parameter keys: A variadic list of keys include in the result.
- warning: Requires Parse Server > 4.5.0.
*/
public func select(_ keys: String...) -> Query<T> {
var mutableQuery = self
if mutableQuery.keys != nil {
mutableQuery.keys = mutableQuery.keys?.union(keys)
} else {
mutableQuery.keys = Set(keys)
}
return mutableQuery
}
/**
Make the query restrict the fields of the returned `ParseObject`s to include only the provided keys.
If this is called multiple times, then all of the keys specified in each of the calls will be included.
- parameter keys: An array of keys to include in the result.
- warning: Requires Parse Server > 4.5.0.
*/
public func select(_ keys: [String]) -> Query<T> {
var mutableQuery = self
if mutableQuery.keys != nil {
mutableQuery.keys = mutableQuery.keys?.union(keys)
} else {
mutableQuery.keys = Set(keys)
}
return mutableQuery
}
/**
An enum that determines the order to sort the results based on a given key.
- parameter keys: An array of keys to order by.
*/
public func order(_ keys: [Order]?) -> Query<T> {
var mutableQuery = self
mutableQuery.order = keys
return mutableQuery
}
/**
A variadic list of fields to receive when receiving a `ParseLiveQuery`.
Suppose the `ParseObject` Player contains three fields name, id and age.
If you are only interested in the change of the name field, you can set `query.fields` to "name".
In this situation, when the change of a Player `ParseObject` fulfills the subscription, only the
name field will be sent to the clients instead of the full Player `ParseObject`.
If this is called multiple times, then all of the keys specified in each of the calls will be received.
- warning: This is only for `ParseLiveQuery`.
- parameter keys: A variadic list of fields to receive back instead of the whole `ParseObject`.
*/
@available(macOS 10.15, iOS 13.0, macCatalyst 13.0, watchOS 6.0, tvOS 13.0, *)
public func fields(_ keys: String...) -> Query<T> {
var mutableQuery = self
if mutableQuery.fields != nil {
mutableQuery.fields = mutableQuery.fields?.union(keys)
} else {
mutableQuery.fields = Set(keys)
}
return mutableQuery
}
/**
A list of fields to receive when receiving a `ParseLiveQuery`.
Suppose the `ParseObject` Player contains three fields name, id and age.
If you are only interested in the change of the name field, you can set `query.fields` to "name".
In this situation, when the change of a Player `ParseObject` fulfills the subscription, only the
name field will be sent to the clients instead of the full Player `ParseObject`.
If this is called multiple times, then all of the keys specified in each of the calls will be received.
- warning: This is only for `ParseLiveQuery`.
- parameter keys: An array of fields to receive back instead of the whole `ParseObject`.
*/
@available(macOS 10.15, iOS 13.0, macCatalyst 13.0, watchOS 6.0, tvOS 13.0, *)
public func fields(_ keys: [String]) -> Query<T> {
var mutableQuery = self
if mutableQuery.fields != nil {
mutableQuery.fields = mutableQuery.fields?.union(keys)
} else {
mutableQuery.fields = Set(keys)
}
return mutableQuery
}
/**
The className of a `ParseObject` to query.
*/
var className: String {
return T.className
}
/**
The className of a `ParseObject` to query.
*/
static var className: String {
return T.className
}
var endpoint: API.Endpoint {
return .objects(className: T.className)
}
enum CodingKeys: String, CodingKey {
case `where`
case method = "_method"
case limit
case skip
case include
case isCount = "count"
case keys
case order
case explain
case hint
case excludeKeys
case readPreference
case includeReadPreference
case subqueryReadPreference
case distinct
case pipeline
}
}
// MARK: Queryable
extension Query: Queryable {
public typealias ResultType = T
/**
Finds objects *synchronously* based on the constructed query and sets an error if there was one.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- throws: An error of type `ParseError`.
- returns: Returns an array of `ParseObject`s that were found.
*/
public func find(options: API.Options = []) throws -> [ResultType] {
try findCommand().execute(options: options)
}
/**
Query plan information for finding objects *synchronously* based on the constructed query and
sets an error if there was one.
- note: An explain query will have many different underlying types. Since Swift is a strongly
typed language, a developer should specify the type expected to be decoded which will be
different for mongoDB and PostgreSQL. One way around this is to use a type-erased wrapper
such as the [AnyCodable](https://github.com/Flight-School/AnyCodable) package.
- parameter options: A set of header options sent to the server. Defaults to an empty set.
- throws: An error of type `ParseError`.
- returns: Returns a response of `Decodable` type.
*/
public func findExplain<U: Decodable>(options: API.Options = []) throws -> [U] {
try findExplainCommand().execute(options: options)
}
/**