FIRQueryTests.mm 102 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import <FirebaseFirestore/FirebaseFirestore.h>
  17. #import <XCTest/XCTest.h>
  18. #import "Firestore/Example/Tests/Util/FSTEventAccumulator.h"
  19. #import "Firestore/Example/Tests/Util/FSTHelpers.h"
  20. #import "Firestore/Example/Tests/Util/FSTIntegrationTestCase.h"
  21. #import "Firestore/Example/Tests/Util/FSTTestingHooks.h"
  22. // TODO(MIEQ) update these imports with public imports when aggregate types are public
  23. #import "Firestore/Source/API/FIRAggregateQuerySnapshot+Internal.h"
  24. #import "Firestore/Source/API/FIRQuery+Internal.h"
  25. @interface FIRQueryTests : FSTIntegrationTestCase
  26. @end
  27. @implementation FIRQueryTests
  28. /**
  29. * Checks that running the query while online (against the backend/emulator) results in the same
  30. * documents as running the query while offline. It also checks that both online and offline
  31. * query result is equal to the expected documents.
  32. *
  33. * @param query The query to check.
  34. * @param expectedDocs Array of document keys that are expected to match the query.
  35. */
  36. - (void)checkOnlineAndOfflineQuery:(FIRQuery *)query matchesResult:(NSArray *)expectedDocs {
  37. FIRQuerySnapshot *docsFromServer = [self readDocumentSetForRef:query
  38. source:FIRFirestoreSourceServer];
  39. FIRQuerySnapshot *docsFromCache = [self readDocumentSetForRef:query
  40. source:FIRFirestoreSourceCache];
  41. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(docsFromServer),
  42. FIRQuerySnapshotGetIDs(docsFromCache));
  43. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(docsFromCache), expectedDocs);
  44. }
  45. - (void)testLimitQueries {
  46. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  47. @"a" : @{@"k" : @"a"},
  48. @"b" : @{@"k" : @"b"},
  49. @"c" : @{@"k" : @"c"}
  50. }];
  51. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:[collRef queryLimitedTo:2]];
  52. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ @{@"k" : @"a"}, @{@"k" : @"b"} ]));
  53. }
  54. - (void)testLimitQueriesWithDescendingSortOrder {
  55. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  56. @"a" : @{@"k" : @"a", @"sort" : @0},
  57. @"b" : @{@"k" : @"b", @"sort" : @1},
  58. @"c" : @{@"k" : @"c", @"sort" : @1},
  59. @"d" : @{@"k" : @"d", @"sort" : @2},
  60. }];
  61. FIRQuerySnapshot *snapshot =
  62. [self readDocumentSetForRef:[[collRef queryOrderedByField:@"sort"
  63. descending:YES] queryLimitedTo:2]];
  64. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  65. (@[ @{@"k" : @"d", @"sort" : @2}, @{@"k" : @"c", @"sort" : @1} ]));
  66. }
  67. - (void)testLimitToLastMustAlsoHaveExplicitOrderBy {
  68. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{}];
  69. FIRQuery *query = [collRef queryLimitedToLast:2];
  70. FSTAssertThrows([query getDocumentsWithCompletion:^(FIRQuerySnapshot *, NSError *){
  71. }],
  72. @"limit(toLast:) queries require specifying at least one OrderBy() clause.");
  73. }
  74. // Two queries that mapped to the same target ID are referred to as
  75. // "mirror queries". An example for a mirror query is a limitToLast()
  76. // query and a limit() query that share the same backend Target ID.
  77. // Since limitToLast() queries are sent to the backend with a modified
  78. // orderBy() clause, they can map to the same target representation as
  79. // limit() query, even if both queries appear separate to the user.
  80. - (void)testListenUnlistenRelistenSequenceOfMirrorQueries {
  81. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  82. @"a" : @{@"k" : @"a", @"sort" : @0},
  83. @"b" : @{@"k" : @"b", @"sort" : @1},
  84. @"c" : @{@"k" : @"c", @"sort" : @1},
  85. @"d" : @{@"k" : @"d", @"sort" : @2},
  86. }];
  87. // Setup a `limit` query.
  88. FIRQuery *limit = [[collRef queryOrderedByField:@"sort" descending:NO] queryLimitedTo:2];
  89. FSTEventAccumulator *limitAccumulator = [FSTEventAccumulator accumulatorForTest:self];
  90. id<FIRListenerRegistration> limitRegistration =
  91. [limit addSnapshotListener:limitAccumulator.valueEventHandler];
  92. // Setup a mirroring `limitToLast` query.
  93. FIRQuery *limitToLast = [[collRef queryOrderedByField:@"sort"
  94. descending:YES] queryLimitedToLast:2];
  95. FSTEventAccumulator *limitToLastAccumulator = [FSTEventAccumulator accumulatorForTest:self];
  96. id<FIRListenerRegistration> limitToLastRegistration =
  97. [limitToLast addSnapshotListener:limitToLastAccumulator.valueEventHandler];
  98. // Verify both queries get expected result.
  99. FIRQuerySnapshot *snapshot = [limitAccumulator awaitEventWithName:@"Snapshot"];
  100. NSArray *expected = @[ @{@"k" : @"a", @"sort" : @0}, @{@"k" : @"b", @"sort" : @1} ];
  101. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  102. snapshot = [limitToLastAccumulator awaitEventWithName:@"Snapshot"];
  103. expected = @[ @{@"k" : @"b", @"sort" : @1}, @{@"k" : @"a", @"sort" : @0} ];
  104. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  105. // Unlisten then re-listen limit query.
  106. [limitRegistration remove];
  107. [limit addSnapshotListener:[limitAccumulator valueEventHandler]];
  108. // Verify limit query still works.
  109. snapshot = [limitAccumulator awaitEventWithName:@"Snapshot"];
  110. expected = @[ @{@"k" : @"a", @"sort" : @0}, @{@"k" : @"b", @"sort" : @1} ];
  111. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  112. // Add a document that would change the result set.
  113. [self addDocumentRef:collRef data:@{@"k" : @"e", @"sort" : @-1}];
  114. // Verify both queries get expected result.
  115. snapshot = [limitAccumulator awaitEventWithName:@"Snapshot"];
  116. expected = @[ @{@"k" : @"e", @"sort" : @-1}, @{@"k" : @"a", @"sort" : @0} ];
  117. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  118. snapshot = [limitToLastAccumulator awaitEventWithName:@"Snapshot"];
  119. expected = @[ @{@"k" : @"a", @"sort" : @0}, @{@"k" : @"e", @"sort" : @-1} ];
  120. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  121. // Unlisten to limitToLast, update a doc, then relisten to limitToLast
  122. [limitToLastRegistration remove];
  123. [self updateDocumentRef:[collRef documentWithPath:@"a"] data:@{@"k" : @"a", @"sort" : @-2}];
  124. [limitToLast addSnapshotListener:[limitToLastAccumulator valueEventHandler]];
  125. // Verify both queries get expected result.
  126. snapshot = [limitAccumulator awaitEventWithName:@"Snapshot"];
  127. expected = @[ @{@"k" : @"a", @"sort" : @-2}, @{@"k" : @"e", @"sort" : @-1} ];
  128. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  129. snapshot = [limitToLastAccumulator awaitEventWithName:@"Snapshot"];
  130. expected = @[ @{@"k" : @"e", @"sort" : @-1}, @{@"k" : @"a", @"sort" : @-2} ];
  131. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  132. }
  133. - (void)testLimitToLastQueriesWithCursors {
  134. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  135. @"a" : @{@"k" : @"a", @"sort" : @0},
  136. @"b" : @{@"k" : @"b", @"sort" : @1},
  137. @"c" : @{@"k" : @"c", @"sort" : @1},
  138. @"d" : @{@"k" : @"d", @"sort" : @2},
  139. }];
  140. FIRQuerySnapshot *snapshot =
  141. [self readDocumentSetForRef:[[[collRef queryOrderedByField:@"sort"] queryLimitedToLast:3]
  142. queryEndingBeforeValues:@[ @2 ]]];
  143. XCTAssertEqualObjects(
  144. FIRQuerySnapshotGetData(snapshot), (@[
  145. @{@"k" : @"a", @"sort" : @0}, @{@"k" : @"b", @"sort" : @1}, @{@"k" : @"c", @"sort" : @1}
  146. ]));
  147. snapshot = [self readDocumentSetForRef:[[[collRef queryOrderedByField:@"sort"]
  148. queryLimitedToLast:3] queryEndingAtValues:@[ @1 ]]];
  149. XCTAssertEqualObjects(
  150. FIRQuerySnapshotGetData(snapshot), (@[
  151. @{@"k" : @"a", @"sort" : @0}, @{@"k" : @"b", @"sort" : @1}, @{@"k" : @"c", @"sort" : @1}
  152. ]));
  153. snapshot = [self readDocumentSetForRef:[[[collRef queryOrderedByField:@"sort"]
  154. queryLimitedToLast:3] queryStartingAtValues:@[ @2 ]]];
  155. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ @{@"k" : @"d", @"sort" : @2} ]));
  156. snapshot =
  157. [self readDocumentSetForRef:[[[collRef queryOrderedByField:@"sort"] queryLimitedToLast:3]
  158. queryStartingAfterValues:@[ @0 ]]];
  159. XCTAssertEqualObjects(
  160. FIRQuerySnapshotGetData(snapshot), (@[
  161. @{@"k" : @"b", @"sort" : @1}, @{@"k" : @"c", @"sort" : @1}, @{@"k" : @"d", @"sort" : @2}
  162. ]));
  163. snapshot =
  164. [self readDocumentSetForRef:[[[collRef queryOrderedByField:@"sort"] queryLimitedToLast:3]
  165. queryStartingAfterValues:@[ @-1 ]]];
  166. XCTAssertEqualObjects(
  167. FIRQuerySnapshotGetData(snapshot), (@[
  168. @{@"k" : @"b", @"sort" : @1}, @{@"k" : @"c", @"sort" : @1}, @{@"k" : @"d", @"sort" : @2}
  169. ]));
  170. }
  171. - (void)testKeyOrderIsDescendingForDescendingInequality {
  172. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  173. @"a" : @{@"foo" : @42},
  174. @"b" : @{@"foo" : @42.0},
  175. @"c" : @{@"foo" : @42},
  176. @"d" : @{@"foo" : @21},
  177. @"e" : @{@"foo" : @21.0},
  178. @"f" : @{@"foo" : @66},
  179. @"g" : @{@"foo" : @66.0},
  180. }];
  181. FIRQuerySnapshot *snapshot =
  182. [self readDocumentSetForRef:[[collRef queryWhereField:@"foo"
  183. isGreaterThan:@21] queryOrderedByField:@"foo"
  184. descending:YES]];
  185. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"g", @"f", @"c", @"b", @"a" ]));
  186. }
  187. - (void)testUnaryFilterQueries {
  188. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  189. @"a" : @{@"null" : [NSNull null], @"nan" : @(NAN)},
  190. @"b" : @{@"null" : [NSNull null], @"nan" : @0},
  191. @"c" : @{@"null" : @NO, @"nan" : @(NAN)}
  192. }];
  193. FIRQuerySnapshot *results =
  194. [self readDocumentSetForRef:[[collRef queryWhereField:@"null"
  195. isEqualTo:[NSNull null]] queryWhereField:@"nan"
  196. isEqualTo:@(NAN)]];
  197. XCTAssertEqualObjects(FIRQuerySnapshotGetData(results),
  198. (@[ @{@"null" : [NSNull null], @"nan" : @(NAN)} ]));
  199. }
  200. - (void)testQueryWithFieldPaths {
  201. FIRCollectionReference *collRef = [self
  202. collectionRefWithDocuments:@{@"a" : @{@"a" : @1}, @"b" : @{@"a" : @2}, @"c" : @{@"a" : @3}}];
  203. FIRQuery *query = [collRef queryWhereFieldPath:[[FIRFieldPath alloc] initWithFields:@[ @"a" ]]
  204. isLessThan:@3];
  205. query = [query queryOrderedByFieldPath:[[FIRFieldPath alloc] initWithFields:@[ @"a" ]]
  206. descending:YES];
  207. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:query];
  208. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"b", @"a" ]));
  209. }
  210. - (void)testQueryWithPredicate {
  211. FIRCollectionReference *collRef = [self
  212. collectionRefWithDocuments:@{@"a" : @{@"a" : @1}, @"b" : @{@"a" : @2}, @"c" : @{@"a" : @3}}];
  213. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"a < 3"];
  214. FIRQuery *query = [collRef queryFilteredUsingPredicate:predicate];
  215. query = [query queryOrderedByFieldPath:[[FIRFieldPath alloc] initWithFields:@[ @"a" ]]
  216. descending:YES];
  217. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:query];
  218. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"b", @"a" ]));
  219. }
  220. - (void)testFilterOnInfinity {
  221. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  222. @"a" : @{@"inf" : @(INFINITY)},
  223. @"b" : @{@"inf" : @(-INFINITY)}
  224. }];
  225. FIRQuerySnapshot *results = [self readDocumentSetForRef:[collRef queryWhereField:@"inf"
  226. isEqualTo:@(INFINITY)]];
  227. XCTAssertEqualObjects(FIRQuerySnapshotGetData(results), (@[ @{@"inf" : @(INFINITY)} ]));
  228. }
  229. - (void)testCanExplicitlySortByDocumentID {
  230. NSDictionary *testDocs = @{
  231. @"a" : @{@"key" : @"a"},
  232. @"b" : @{@"key" : @"b"},
  233. @"c" : @{@"key" : @"c"},
  234. };
  235. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  236. // Ideally this would be descending to validate it's different than
  237. // the default, but that requires an extra index
  238. FIRQuerySnapshot *docs =
  239. [self readDocumentSetForRef:[collection queryOrderedByFieldPath:[FIRFieldPath documentID]]];
  240. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs),
  241. (@[ testDocs[@"a"], testDocs[@"b"], testDocs[@"c"] ]));
  242. }
  243. - (void)testCanQueryByDocumentID {
  244. NSDictionary *testDocs = @{
  245. @"aa" : @{@"key" : @"aa"},
  246. @"ab" : @{@"key" : @"ab"},
  247. @"ba" : @{@"key" : @"ba"},
  248. @"bb" : @{@"key" : @"bb"},
  249. };
  250. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  251. FIRQuerySnapshot *docs =
  252. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  253. isEqualTo:@"ab"]];
  254. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs), (@[ testDocs[@"ab"] ]));
  255. }
  256. - (void)testCanQueryByDocumentIDs {
  257. NSDictionary *testDocs = @{
  258. @"aa" : @{@"key" : @"aa"},
  259. @"ab" : @{@"key" : @"ab"},
  260. @"ba" : @{@"key" : @"ba"},
  261. @"bb" : @{@"key" : @"bb"},
  262. };
  263. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  264. FIRQuerySnapshot *docs =
  265. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  266. isEqualTo:@"ab"]];
  267. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs), (@[ testDocs[@"ab"] ]));
  268. docs = [self readDocumentSetForRef:[[collection queryWhereFieldPath:[FIRFieldPath documentID]
  269. isGreaterThan:@"aa"]
  270. queryWhereFieldPath:[FIRFieldPath documentID]
  271. isLessThanOrEqualTo:@"ba"]];
  272. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs), (@[ testDocs[@"ab"], testDocs[@"ba"] ]));
  273. }
  274. - (void)testCanQueryByDocumentIDsUsingRefs {
  275. NSDictionary *testDocs = @{
  276. @"aa" : @{@"key" : @"aa"},
  277. @"ab" : @{@"key" : @"ab"},
  278. @"ba" : @{@"key" : @"ba"},
  279. @"bb" : @{@"key" : @"bb"},
  280. };
  281. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  282. FIRQuerySnapshot *docs = [self
  283. readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  284. isEqualTo:[collection documentWithPath:@"ab"]]];
  285. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs), (@[ testDocs[@"ab"] ]));
  286. docs = [self
  287. readDocumentSetForRef:[[collection queryWhereFieldPath:[FIRFieldPath documentID]
  288. isGreaterThan:[collection documentWithPath:@"aa"]]
  289. queryWhereFieldPath:[FIRFieldPath documentID]
  290. isLessThanOrEqualTo:[collection documentWithPath:@"ba"]]];
  291. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs), (@[ testDocs[@"ab"], testDocs[@"ba"] ]));
  292. }
  293. - (void)testWatchSurvivesNetworkDisconnect {
  294. XCTestExpectation *testExpectiation =
  295. [self expectationWithDescription:@"testWatchSurvivesNetworkDisconnect"];
  296. FIRCollectionReference *collectionRef = [self collectionRef];
  297. FIRDocumentReference *docRef = [collectionRef documentWithAutoID];
  298. FIRFirestore *firestore = collectionRef.firestore;
  299. [collectionRef
  300. addSnapshotListenerWithIncludeMetadataChanges:YES
  301. listener:^(FIRQuerySnapshot *snapshot, NSError *error) {
  302. XCTAssertNil(error);
  303. if (!snapshot.empty && !snapshot.metadata.fromCache) {
  304. [testExpectiation fulfill];
  305. }
  306. }];
  307. [firestore disableNetworkWithCompletion:^(NSError *error) {
  308. XCTAssertNil(error);
  309. [docRef setData:@{@"foo" : @"bar"}];
  310. [firestore enableNetworkWithCompletion:^(NSError *error) {
  311. XCTAssertNil(error);
  312. }];
  313. }];
  314. [self awaitExpectations];
  315. }
  316. - (void)testQueriesFireFromCacheWhenOffline {
  317. NSDictionary *testDocs = @{
  318. @"a" : @{@"foo" : @1},
  319. };
  320. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  321. id<FIRListenerRegistration> registration = [collection
  322. addSnapshotListenerWithIncludeMetadataChanges:YES
  323. listener:self.eventAccumulator.valueEventHandler];
  324. FIRQuerySnapshot *querySnap = [self.eventAccumulator awaitEventWithName:@"initial event"];
  325. XCTAssertEqualObjects(FIRQuerySnapshotGetData(querySnap), @[ @{@"foo" : @1} ]);
  326. XCTAssertEqual(querySnap.metadata.isFromCache, NO);
  327. [self disableNetwork];
  328. querySnap = [self.eventAccumulator awaitEventWithName:@"offline event with isFromCache=YES"];
  329. XCTAssertEqual(querySnap.metadata.isFromCache, YES);
  330. [self enableNetwork];
  331. querySnap = [self.eventAccumulator awaitEventWithName:@"back online event with isFromCache=NO"];
  332. XCTAssertEqual(querySnap.metadata.isFromCache, NO);
  333. [registration remove];
  334. }
  335. - (void)testQueriesCanRaiseInitialSnapshotFromCachedEmptyResults {
  336. FIRCollectionReference *collection = [self collectionRefWithDocuments:@{}];
  337. // Populate the cache with empty query result.
  338. FIRQuerySnapshot *querySnapshotA = [self readDocumentSetForRef:collection];
  339. XCTAssertFalse(querySnapshotA.metadata.fromCache);
  340. XCTAssertEqualObjects(FIRQuerySnapshotGetData(querySnapshotA), @[]);
  341. // Add a snapshot listener whose first event should be raised from cache.
  342. id<FIRListenerRegistration> registration = [collection
  343. addSnapshotListenerWithIncludeMetadataChanges:YES
  344. listener:self.eventAccumulator.valueEventHandler];
  345. FIRQuerySnapshot *querySnapshotB = [self.eventAccumulator awaitEventWithName:@"initial event"];
  346. XCTAssertTrue(querySnapshotB.metadata.fromCache);
  347. XCTAssertEqualObjects(FIRQuerySnapshotGetData(querySnapshotB), @[]);
  348. [registration remove];
  349. }
  350. - (void)testQueriesCanRaiseInitialSnapshotFromEmptyDueToDeleteCachedResults {
  351. NSDictionary *testDocs = @{
  352. @"a" : @{@"foo" : @1},
  353. };
  354. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  355. // Populate the cache with a single document.
  356. FIRQuerySnapshot *querySnapshotA = [self readDocumentSetForRef:collection];
  357. XCTAssertFalse(querySnapshotA.metadata.fromCache);
  358. XCTAssertEqualObjects(FIRQuerySnapshotGetData(querySnapshotA), @[ @{@"foo" : @1} ]);
  359. // Delete the document, making the cached query result empty.
  360. FIRDocumentReference *docRef = [collection documentWithPath:@"a"];
  361. [self deleteDocumentRef:docRef];
  362. // Add a snapshot listener whose first event should be raised from cache.
  363. id<FIRListenerRegistration> registration = [collection
  364. addSnapshotListenerWithIncludeMetadataChanges:YES
  365. listener:self.eventAccumulator.valueEventHandler];
  366. FIRQuerySnapshot *querySnapshotB = [self.eventAccumulator awaitEventWithName:@"initial event"];
  367. XCTAssertTrue(querySnapshotB.metadata.fromCache);
  368. XCTAssertEqualObjects(FIRQuerySnapshotGetData(querySnapshotB), @[]);
  369. [registration remove];
  370. }
  371. - (void)testDocumentChangesUseNSNotFound {
  372. NSDictionary *testDocs = @{
  373. @"a" : @{@"foo" : @1},
  374. };
  375. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  376. id<FIRListenerRegistration> registration =
  377. [collection addSnapshotListener:self.eventAccumulator.valueEventHandler];
  378. FIRQuerySnapshot *querySnap = [self.eventAccumulator awaitEventWithName:@"initial event"];
  379. XCTAssertEqual(querySnap.documentChanges.count, 1ul);
  380. FIRDocumentChange *change = querySnap.documentChanges[0];
  381. XCTAssertEqual(change.oldIndex, NSNotFound);
  382. XCTAssertEqual(change.newIndex, 0ul);
  383. FIRDocumentReference *doc = change.document.reference;
  384. [self deleteDocumentRef:doc];
  385. querySnap = [self.eventAccumulator awaitEventWithName:@"delete"];
  386. XCTAssertEqual(querySnap.documentChanges.count, 1ul);
  387. change = querySnap.documentChanges[0];
  388. XCTAssertEqual(change.oldIndex, 0ul);
  389. XCTAssertEqual(change.newIndex, NSNotFound);
  390. [registration remove];
  391. }
  392. - (void)testCanHaveMultipleMutationsWhileOffline {
  393. FIRCollectionReference *col = [self collectionRef];
  394. // set a few docs to known values
  395. NSDictionary *initialDocs = @{@"doc1" : @{@"key1" : @"value1"}, @"doc2" : @{@"key2" : @"value2"}};
  396. [self writeAllDocuments:initialDocs toCollection:col];
  397. // go offline for the rest of this test
  398. [self disableNetwork];
  399. // apply *multiple* mutations while offline
  400. [[col documentWithPath:@"doc1"] setData:@{@"key1b" : @"value1b"}];
  401. [[col documentWithPath:@"doc2"] setData:@{@"key2b" : @"value2b"}];
  402. FIRQuerySnapshot *result = [self readDocumentSetForRef:col];
  403. XCTAssertEqualObjects(FIRQuerySnapshotGetData(result), (@[
  404. @{@"key1b" : @"value1b"},
  405. @{@"key2b" : @"value2b"},
  406. ]));
  407. }
  408. - (void)testQueriesCanUseNotEqualFilters {
  409. // These documents are ordered by value in "zip" since notEquals filter is an inequality, which
  410. // results in documents being sorted by value.
  411. NSDictionary *testDocs = @{
  412. @"a" : @{@"zip" : @(NAN)},
  413. @"b" : @{@"zip" : @91102},
  414. @"c" : @{@"zip" : @98101},
  415. @"d" : @{@"zip" : @98103},
  416. @"e" : @{@"zip" : @[ @98101 ]},
  417. @"f" : @{@"zip" : @[ @98101, @98102 ]},
  418. @"g" : @{@"zip" : @[ @"98101", @{@"zip" : @98101} ]},
  419. @"h" : @{@"zip" : @{@"code" : @500}},
  420. @"i" : @{@"zip" : [NSNull null]},
  421. @"j" : @{@"code" : @500},
  422. };
  423. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  424. // Search for zips not matching 98101.
  425. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  426. isNotEqualTo:@98101]];
  427. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  428. testDocs[@"a"], testDocs[@"b"], testDocs[@"d"], testDocs[@"e"],
  429. testDocs[@"f"], testDocs[@"g"], testDocs[@"h"]
  430. ]));
  431. // With objects.
  432. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  433. isNotEqualTo:@{@"code" : @500}]];
  434. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  435. testDocs[@"a"], testDocs[@"b"], testDocs[@"c"], testDocs[@"d"],
  436. testDocs[@"e"], testDocs[@"f"], testDocs[@"g"]
  437. ]));
  438. // With null.
  439. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  440. isNotEqualTo:@[ [NSNull null] ]]];
  441. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  442. testDocs[@"a"], testDocs[@"b"], testDocs[@"c"], testDocs[@"d"],
  443. testDocs[@"e"], testDocs[@"f"], testDocs[@"g"], testDocs[@"h"]
  444. ]));
  445. // With NAN.
  446. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip" isNotEqualTo:@(NAN)]];
  447. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  448. testDocs[@"b"], testDocs[@"c"], testDocs[@"d"], testDocs[@"e"],
  449. testDocs[@"f"], testDocs[@"g"], testDocs[@"h"]
  450. ]));
  451. }
  452. - (void)testQueriesCanUseNotEqualFiltersWithDocIds {
  453. NSDictionary *testDocs = @{
  454. @"aa" : @{@"key" : @"aa"},
  455. @"ab" : @{@"key" : @"ab"},
  456. @"ba" : @{@"key" : @"ba"},
  457. @"bb" : @{@"key" : @"bb"},
  458. };
  459. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  460. FIRQuerySnapshot *snapshot =
  461. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  462. isNotEqualTo:@"aa"]];
  463. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  464. (@[ testDocs[@"ab"], testDocs[@"ba"], testDocs[@"bb"] ]));
  465. }
  466. - (void)testQueriesCanUseArrayContainsFilters {
  467. NSDictionary *testDocs = @{
  468. @"a" : @{@"array" : @[ @42 ]},
  469. @"b" : @{@"array" : @[ @"a", @42, @"c" ]},
  470. @"c" : @{@"array" : @[ @41.999, @"42", @{@"a" : @[ @42 ]} ]},
  471. @"d" : @{@"array" : @[ @42 ], @"array2" : @[ @"bingo" ]},
  472. @"e" : @{@"array" : @[ [NSNull null] ]},
  473. @"f" : @{@"array" : @[ @(NAN) ]},
  474. };
  475. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  476. // Search for 42
  477. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  478. arrayContains:@42]];
  479. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  480. (@[ testDocs[@"a"], testDocs[@"b"], testDocs[@"d"] ]));
  481. // With null.
  482. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  483. arrayContains:[NSNull null]]];
  484. XCTAssertTrue(snapshot.isEmpty);
  485. // With NAN.
  486. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  487. arrayContains:@(NAN)]];
  488. XCTAssertTrue(snapshot.isEmpty);
  489. }
  490. - (void)testQueriesCanUseInFilters {
  491. NSDictionary *testDocs = @{
  492. @"a" : @{@"zip" : @98101},
  493. @"b" : @{@"zip" : @91102},
  494. @"c" : @{@"zip" : @98103},
  495. @"d" : @{@"zip" : @[ @98101 ]},
  496. @"e" : @{@"zip" : @[ @"98101", @{@"zip" : @98101} ]},
  497. @"f" : @{@"zip" : @{@"code" : @500}},
  498. @"g" : @{@"zip" : @[ @98101, @98102 ]},
  499. @"h" : @{@"zip" : [NSNull null]},
  500. @"i" : @{@"zip" : @(NAN)}
  501. };
  502. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  503. // Search for zips matching 98101, 98103, and [98101, 98102].
  504. FIRQuerySnapshot *snapshot = [self
  505. readDocumentSetForRef:[collection queryWhereField:@"zip"
  506. in:@[ @98101, @98103, @[ @98101, @98102 ] ]]];
  507. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  508. (@[ testDocs[@"a"], testDocs[@"c"], testDocs[@"g"] ]));
  509. // With objects
  510. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  511. in:@[ @{@"code" : @500} ]]];
  512. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"f"] ]));
  513. // With null.
  514. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip" in:@[ [NSNull null] ]]];
  515. XCTAssertTrue(snapshot.isEmpty);
  516. // With null and a value.
  517. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  518. in:@[ [NSNull null], @98101 ]]];
  519. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"a"] ]));
  520. // With NAN.
  521. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip" in:@[ @(NAN) ]]];
  522. XCTAssertTrue(snapshot.isEmpty);
  523. // With NAN and a value.
  524. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  525. in:@[ @(NAN), @98101 ]]];
  526. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"a"] ]));
  527. }
  528. - (void)testQueriesCanUseInFiltersWithDocIds {
  529. NSDictionary *testDocs = @{
  530. @"aa" : @{@"key" : @"aa"},
  531. @"ab" : @{@"key" : @"ab"},
  532. @"ba" : @{@"key" : @"ba"},
  533. @"bb" : @{@"key" : @"bb"},
  534. };
  535. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  536. FIRQuerySnapshot *snapshot =
  537. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  538. in:@[ @"aa", @"ab" ]]];
  539. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"aa"], testDocs[@"ab"] ]));
  540. }
  541. - (void)testQueriesCanUseNotInFilters {
  542. // These documents are ordered by value in "zip" since the NOT_IN filter is an inequality, which
  543. // results in documents being sorted by value.
  544. NSDictionary *testDocs = @{
  545. @"a" : @{@"zip" : @(NAN)},
  546. @"b" : @{@"zip" : @91102},
  547. @"c" : @{@"zip" : @98101},
  548. @"d" : @{@"zip" : @98103},
  549. @"e" : @{@"zip" : @[ @98101 ]},
  550. @"f" : @{@"zip" : @[ @98101, @98102 ]},
  551. @"g" : @{@"zip" : @[ @"98101", @{@"zip" : @98101} ]},
  552. @"h" : @{@"zip" : @{@"code" : @500}},
  553. @"i" : @{@"zip" : [NSNull null]},
  554. @"j" : @{@"code" : @500},
  555. };
  556. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  557. // Search for zips not matching 98101, 98103, and [98101, 98102].
  558. FIRQuerySnapshot *snapshot = [self
  559. readDocumentSetForRef:[collection queryWhereField:@"zip"
  560. notIn:@[ @98101, @98103, @[ @98101, @98102 ] ]]];
  561. XCTAssertEqualObjects(
  562. FIRQuerySnapshotGetData(snapshot),
  563. (@[ testDocs[@"a"], testDocs[@"b"], testDocs[@"e"], testDocs[@"g"], testDocs[@"h"] ]));
  564. // With objects.
  565. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  566. notIn:@[ @{@"code" : @500} ]]];
  567. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  568. testDocs[@"a"], testDocs[@"b"], testDocs[@"c"], testDocs[@"d"],
  569. testDocs[@"e"], testDocs[@"f"], testDocs[@"g"]
  570. ]));
  571. // With null.
  572. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  573. notIn:@[ [NSNull null] ]]];
  574. XCTAssertTrue(snapshot.isEmpty);
  575. // With NAN.
  576. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip" notIn:@[ @(NAN) ]]];
  577. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  578. testDocs[@"b"], testDocs[@"c"], testDocs[@"d"], testDocs[@"e"],
  579. testDocs[@"f"], testDocs[@"g"], testDocs[@"h"]
  580. ]));
  581. // With NAN and a number.
  582. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  583. notIn:@[ @(NAN), @98101 ]]];
  584. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  585. testDocs[@"b"], testDocs[@"d"], testDocs[@"e"], testDocs[@"f"],
  586. testDocs[@"g"], testDocs[@"h"]
  587. ]));
  588. }
  589. - (void)testQueriesCanUseNotInFiltersWithDocIds {
  590. NSDictionary *testDocs = @{
  591. @"aa" : @{@"key" : @"aa"},
  592. @"ab" : @{@"key" : @"ab"},
  593. @"ba" : @{@"key" : @"ba"},
  594. @"bb" : @{@"key" : @"bb"},
  595. };
  596. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  597. FIRQuerySnapshot *snapshot =
  598. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  599. notIn:@[ @"aa", @"ab" ]]];
  600. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"ba"], testDocs[@"bb"] ]));
  601. }
  602. - (void)testQueriesCanUseArrayContainsAnyFilters {
  603. NSDictionary *testDocs = @{
  604. @"a" : @{@"array" : @[ @42 ]},
  605. @"b" : @{@"array" : @[ @"a", @42, @"c" ]},
  606. @"c" : @{@"array" : @[ @41.999, @"42", @{@"a" : @[ @42 ]} ]},
  607. @"d" : @{@"array" : @[ @42 ], @"array2" : @[ @"bingo" ]},
  608. @"e" : @{@"array" : @[ @43 ]},
  609. @"f" : @{@"array" : @[ @{@"a" : @42} ]},
  610. @"g" : @{@"array" : @42},
  611. @"h" : @{@"array" : @[ [NSNull null] ]},
  612. @"i" : @{@"array" : @[ @(NAN) ]},
  613. };
  614. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  615. // Search for zips matching [42, 43].
  616. FIRQuerySnapshot *snapshot = [self
  617. readDocumentSetForRef:[collection queryWhereField:@"array" arrayContainsAny:@[ @42, @43 ]]];
  618. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  619. (@[ testDocs[@"a"], testDocs[@"b"], testDocs[@"d"], testDocs[@"e"] ]));
  620. // With objects.
  621. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  622. arrayContainsAny:@[ @{@"a" : @42} ]]];
  623. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  624. testDocs[@"f"],
  625. ]));
  626. // With null.
  627. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  628. arrayContainsAny:@[ [NSNull null] ]]];
  629. XCTAssertTrue(snapshot.isEmpty);
  630. // With null and a value.
  631. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  632. arrayContainsAny:@[ [NSNull null], @43 ]]];
  633. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"e"] ]));
  634. // With NAN.
  635. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  636. arrayContainsAny:@[ @(NAN) ]]];
  637. XCTAssertTrue(snapshot.isEmpty);
  638. // With NAN and a value.
  639. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  640. arrayContainsAny:@[ @(NAN), @43 ]]];
  641. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"e"] ]));
  642. }
  643. - (void)testCollectionGroupQueries {
  644. // Use .document() to get a random collection group name to use but ensure it starts with 'b'
  645. // for predictable ordering.
  646. NSString *collectionGroup = [NSString
  647. stringWithFormat:@"b%@", [[self.db collectionWithPath:@"foo"] documentWithAutoID].documentID];
  648. NSArray *docPaths = @[
  649. @"abc/123/${collectionGroup}/cg-doc1", @"abc/123/${collectionGroup}/cg-doc2",
  650. @"${collectionGroup}/cg-doc3", @"${collectionGroup}/cg-doc4",
  651. @"def/456/${collectionGroup}/cg-doc5", @"${collectionGroup}/virtual-doc/nested-coll/not-cg-doc",
  652. @"x${collectionGroup}/not-cg-doc", @"${collectionGroup}x/not-cg-doc",
  653. @"abc/123/${collectionGroup}x/not-cg-doc", @"abc/123/x${collectionGroup}/not-cg-doc",
  654. @"abc/${collectionGroup}"
  655. ];
  656. FIRWriteBatch *batch = [self.db batch];
  657. for (NSString *docPath in docPaths) {
  658. NSString *path = [docPath stringByReplacingOccurrencesOfString:@"${collectionGroup}"
  659. withString:collectionGroup];
  660. [batch setData:@{@"x" : @1} forDocument:[self.db documentWithPath:path]];
  661. }
  662. [self commitWriteBatch:batch];
  663. FIRQuerySnapshot *querySnapshot =
  664. [self readDocumentSetForRef:[self.db collectionGroupWithID:collectionGroup]];
  665. NSArray<NSString *> *ids = FIRQuerySnapshotGetIDs(querySnapshot);
  666. XCTAssertEqualObjects(ids, (@[ @"cg-doc1", @"cg-doc2", @"cg-doc3", @"cg-doc4", @"cg-doc5" ]));
  667. }
  668. - (void)testCollectionGroupQueriesWithStartAtEndAtWithArbitraryDocumentIDs {
  669. // Use .document() to get a random collection group name to use but ensure it starts with 'b'
  670. // for predictable ordering.
  671. NSString *collectionGroup = [NSString
  672. stringWithFormat:@"b%@", [[self.db collectionWithPath:@"foo"] documentWithAutoID].documentID];
  673. NSArray *docPaths = @[
  674. @"a/a/${collectionGroup}/cg-doc1", @"a/b/a/b/${collectionGroup}/cg-doc2",
  675. @"a/b/${collectionGroup}/cg-doc3", @"a/b/c/d/${collectionGroup}/cg-doc4",
  676. @"a/c/${collectionGroup}/cg-doc5", @"${collectionGroup}/cg-doc6", @"a/b/nope/nope"
  677. ];
  678. FIRWriteBatch *batch = [self.db batch];
  679. for (NSString *docPath in docPaths) {
  680. NSString *path = [docPath stringByReplacingOccurrencesOfString:@"${collectionGroup}"
  681. withString:collectionGroup];
  682. [batch setData:@{@"x" : @1} forDocument:[self.db documentWithPath:path]];
  683. }
  684. [self commitWriteBatch:batch];
  685. FIRQuerySnapshot *querySnapshot = [self
  686. readDocumentSetForRef:[[[[self.db collectionGroupWithID:collectionGroup]
  687. queryOrderedByFieldPath:[FIRFieldPath documentID]]
  688. queryStartingAfterValues:@[ @"a/b" ]]
  689. queryEndingBeforeValues:@[
  690. [NSString stringWithFormat:@"a/b/%@/cg-doc3", collectionGroup]
  691. ]]];
  692. NSArray<NSString *> *ids = FIRQuerySnapshotGetIDs(querySnapshot);
  693. XCTAssertEqualObjects(ids, (@[ @"cg-doc2" ]));
  694. }
  695. - (void)testCollectionGroupQueriesWithWhereFiltersOnArbitraryDocumentIDs {
  696. // Use .document() to get a random collection group name to use but ensure it starts with 'b'
  697. // for predictable ordering.
  698. NSString *collectionGroup = [NSString
  699. stringWithFormat:@"b%@", [[self.db collectionWithPath:@"foo"] documentWithAutoID].documentID];
  700. NSArray *docPaths = @[
  701. @"a/a/${collectionGroup}/cg-doc1", @"a/b/a/b/${collectionGroup}/cg-doc2",
  702. @"a/b/${collectionGroup}/cg-doc3", @"a/b/c/d/${collectionGroup}/cg-doc4",
  703. @"a/c/${collectionGroup}/cg-doc5", @"${collectionGroup}/cg-doc6", @"a/b/nope/nope"
  704. ];
  705. FIRWriteBatch *batch = [self.db batch];
  706. for (NSString *docPath in docPaths) {
  707. NSString *path = [docPath stringByReplacingOccurrencesOfString:@"${collectionGroup}"
  708. withString:collectionGroup];
  709. [batch setData:@{@"x" : @1} forDocument:[self.db documentWithPath:path]];
  710. }
  711. [self commitWriteBatch:batch];
  712. FIRQuerySnapshot *querySnapshot = [self
  713. readDocumentSetForRef:[[[self.db collectionGroupWithID:collectionGroup]
  714. queryWhereFieldPath:[FIRFieldPath documentID]
  715. isGreaterThanOrEqualTo:@"a/b"]
  716. queryWhereFieldPath:[FIRFieldPath documentID]
  717. isLessThan:[NSString stringWithFormat:@"a/b/%@/cg-doc3",
  718. collectionGroup]]];
  719. NSArray<NSString *> *ids = FIRQuerySnapshotGetIDs(querySnapshot);
  720. XCTAssertEqualObjects(ids, (@[ @"cg-doc2" ]));
  721. }
  722. - (void)testOrQueries {
  723. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  724. @"doc1" : @{@"a" : @1, @"b" : @0},
  725. @"doc2" : @{@"a" : @2, @"b" : @1},
  726. @"doc3" : @{@"a" : @3, @"b" : @2},
  727. @"doc4" : @{@"a" : @1, @"b" : @3},
  728. @"doc5" : @{@"a" : @1, @"b" : @1}
  729. }];
  730. // Two equalities: a==1 || b==1.
  731. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  732. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter filterWhereField:@"b" isEqualTo:@1]
  733. ]];
  734. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  735. matchesResult:@[ @"doc1", @"doc2", @"doc4", @"doc5" ]];
  736. // (a==1 && b==0) || (a==3 && b==2)
  737. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  738. [FIRFilter andFilterWithFilters:@[
  739. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter filterWhereField:@"b" isEqualTo:@0]
  740. ]],
  741. [FIRFilter andFilterWithFilters:@[
  742. [FIRFilter filterWhereField:@"a" isEqualTo:@3], [FIRFilter filterWhereField:@"b" isEqualTo:@2]
  743. ]]
  744. ]];
  745. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  746. matchesResult:@[ @"doc1", @"doc3" ]];
  747. // a==1 && (b==0 || b==3).
  748. FIRFilter *filter3 = [FIRFilter andFilterWithFilters:@[
  749. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter orFilterWithFilters:@[
  750. [FIRFilter filterWhereField:@"b" isEqualTo:@0], [FIRFilter filterWhereField:@"b" isEqualTo:@3]
  751. ]]
  752. ]];
  753. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter3]
  754. matchesResult:@[ @"doc1", @"doc4" ]];
  755. // (a==2 || b==2) && (a==3 || b==3)
  756. FIRFilter *filter4 = [FIRFilter andFilterWithFilters:@[
  757. [FIRFilter orFilterWithFilters:@[
  758. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" isEqualTo:@2]
  759. ]],
  760. [FIRFilter orFilterWithFilters:@[
  761. [FIRFilter filterWhereField:@"a" isEqualTo:@3], [FIRFilter filterWhereField:@"b" isEqualTo:@3]
  762. ]]
  763. ]];
  764. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter4] matchesResult:@[ @"doc3" ]];
  765. // Test with limits without orderBy (the __name__ ordering is the tie breaker).
  766. FIRFilter *filter5 = [FIRFilter orFilterWithFilters:@[
  767. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" isEqualTo:@1]
  768. ]];
  769. [self checkOnlineAndOfflineQuery:[[collRef queryWhereFilter:filter5] queryLimitedTo:1]
  770. matchesResult:@[ @"doc2" ]];
  771. }
  772. - (void)testOrQueriesWithCompositeIndexes {
  773. // TODO(orquery): Enable this test against production when possible.
  774. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  775. "Skip this test if running against production because order-by-equality is not "
  776. "supported yet.");
  777. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  778. @"doc1" : @{@"a" : @1, @"b" : @0},
  779. @"doc2" : @{@"a" : @2, @"b" : @1},
  780. @"doc3" : @{@"a" : @3, @"b" : @2},
  781. @"doc4" : @{@"a" : @1, @"b" : @3},
  782. @"doc5" : @{@"a" : @1, @"b" : @1}
  783. }];
  784. // with one inequality: a>2 || b==1.
  785. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  786. [FIRFilter filterWhereField:@"a" isGreaterThan:@2], [FIRFilter filterWhereField:@"b"
  787. isEqualTo:@1]
  788. ]];
  789. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  790. matchesResult:@[ @"doc5", @"doc2", @"doc3" ]];
  791. // Test with limits (implicit order by ASC): (a==1) || (b > 0) LIMIT 2
  792. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  793. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter filterWhereField:@"b"
  794. isGreaterThan:@0]
  795. ]];
  796. [self checkOnlineAndOfflineQuery:[[collRef queryWhereFilter:filter2] queryLimitedTo:2]
  797. matchesResult:@[ @"doc1", @"doc2" ]];
  798. // Test with limits (explicit order by): (a==1) || (b > 0) LIMIT_TO_LAST 2
  799. // Note: The public query API does not allow implicit ordering when limitToLast is used.
  800. FIRFilter *filter3 = [FIRFilter orFilterWithFilters:@[
  801. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter filterWhereField:@"b"
  802. isGreaterThan:@0]
  803. ]];
  804. [self checkOnlineAndOfflineQuery:[[[collRef queryWhereFilter:filter3] queryLimitedToLast:2]
  805. queryOrderedByField:@"b"]
  806. matchesResult:@[ @"doc3", @"doc4" ]];
  807. // Test with limits (explicit order by ASC): (a==2) || (b == 1) ORDER BY a LIMIT 1
  808. FIRFilter *filter4 = [FIRFilter orFilterWithFilters:@[
  809. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" isEqualTo:@1]
  810. ]];
  811. [self checkOnlineAndOfflineQuery:[[[collRef queryWhereFilter:filter4] queryLimitedTo:1]
  812. queryOrderedByField:@"a"]
  813. matchesResult:@[ @"doc5" ]];
  814. // Test with limits (explicit order by DESC): (a==2) || (b == 1) ORDER BY a LIMIT_TO_LAST 1
  815. FIRFilter *filter5 = [FIRFilter orFilterWithFilters:@[
  816. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" isEqualTo:@1]
  817. ]];
  818. [self checkOnlineAndOfflineQuery:[[[collRef queryWhereFilter:filter5] queryLimitedToLast:1]
  819. queryOrderedByField:@"a"]
  820. matchesResult:@[ @"doc2" ]];
  821. }
  822. - (void)testOrQueriesWithIn {
  823. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  824. @"doc1" : @{@"a" : @1, @"b" : @0},
  825. @"doc2" : @{@"b" : @1},
  826. @"doc3" : @{@"a" : @3, @"b" : @2},
  827. @"doc4" : @{@"a" : @1, @"b" : @3},
  828. @"doc5" : @{@"a" : @1},
  829. @"doc6" : @{@"a" : @2}
  830. }];
  831. // a==2 || b in [2,3]
  832. FIRFilter *filter = [FIRFilter orFilterWithFilters:@[
  833. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" in:@[ @2, @3 ]]
  834. ]];
  835. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter]
  836. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  837. }
  838. - (void)testOrQueriesWithNotIn {
  839. // TODO(orquery): Enable this test against production when possible.
  840. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  841. "Skip this test if running against production because it results in a 'missing index' "
  842. "error. The Firestore Emulator, however, does serve these queries");
  843. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  844. @"doc1" : @{@"a" : @1, @"b" : @0},
  845. @"doc2" : @{@"b" : @1},
  846. @"doc3" : @{@"a" : @3, @"b" : @2},
  847. @"doc4" : @{@"a" : @1, @"b" : @3},
  848. @"doc5" : @{@"a" : @1},
  849. @"doc6" : @{@"a" : @2}
  850. }];
  851. // a==2 || b not-in [2,3]
  852. // Has implicit orderBy b.
  853. FIRFilter *filter = [FIRFilter orFilterWithFilters:@[
  854. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b"
  855. notIn:@[ @2, @3 ]]
  856. ]];
  857. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter]
  858. matchesResult:@[ @"doc1", @"doc2" ]];
  859. }
  860. - (void)testOrQueriesWithArrayMembership {
  861. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  862. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  863. @"doc2" : @{@"b" : @[ @1 ]},
  864. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ]},
  865. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  866. @"doc5" : @{@"a" : @1},
  867. @"doc6" : @{@"a" : @2}
  868. }];
  869. // a==2 || b array-contains 7
  870. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  871. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b"
  872. arrayContains:@7]
  873. ]];
  874. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  875. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  876. // a==2 || b array-contains-any [0, 3]
  877. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  878. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b"
  879. arrayContainsAny:@[ @0, @3 ]]
  880. ]];
  881. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  882. matchesResult:@[ @"doc1", @"doc4", @"doc6" ]];
  883. }
  884. - (void)testMultipleInOps {
  885. // TODO(orquery): Enable this test against production when possible.
  886. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  887. "Skip this test if running against production because it's not yet supported.");
  888. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  889. @"doc1" : @{@"a" : @1, @"b" : @0},
  890. @"doc2" : @{@"b" : @1},
  891. @"doc3" : @{@"a" : @3, @"b" : @2},
  892. @"doc4" : @{@"a" : @1, @"b" : @3},
  893. @"doc5" : @{@"a" : @1},
  894. @"doc6" : @{@"a" : @2}
  895. }];
  896. // Two IN operations on different fields with disjunction.
  897. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  898. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  899. in:@[ @0, @2 ]]
  900. ]];
  901. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  902. matchesResult:@[ @"doc1", @"doc3", @"doc6" ]];
  903. // Two IN operations on the same field with disjunction.
  904. // a IN [0,3] || a IN [0,2] should union them (similar to: a IN [0,2,3]).
  905. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  906. [FIRFilter filterWhereField:@"a" in:@[ @0, @3 ]], [FIRFilter filterWhereField:@"a"
  907. in:@[ @0, @2 ]]
  908. ]];
  909. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  910. matchesResult:@[ @"doc3", @"doc6" ]];
  911. }
  912. - (void)testUsingInWithArrayContainsAny {
  913. // TODO(orquery): Enable this test against production when possible.
  914. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  915. "Skip this test if running against production because it's not yet supported.");
  916. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  917. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  918. @"doc2" : @{@"b" : @[ @1 ]},
  919. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ], @"c" : @10},
  920. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  921. @"doc5" : @{@"a" : @1},
  922. @"doc6" : @{@"a" : @2, @"c" : @20}
  923. }];
  924. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  925. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  926. arrayContainsAny:@[ @0, @7 ]]
  927. ]];
  928. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  929. matchesResult:@[ @"doc1", @"doc3", @"doc4", @"doc6" ]];
  930. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  931. [FIRFilter andFilterWithFilters:@[
  932. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"c"
  933. isEqualTo:@10]
  934. ]],
  935. [FIRFilter filterWhereField:@"b" arrayContainsAny:@[ @0, @7 ]]
  936. ]];
  937. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  938. matchesResult:@[ @"doc1", @"doc3", @"doc4" ]];
  939. }
  940. - (void)testUseInWithArrayContains {
  941. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  942. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  943. @"doc2" : @{@"b" : @[ @1 ]},
  944. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ]},
  945. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  946. @"doc5" : @{@"a" : @1},
  947. @"doc6" : @{@"a" : @2}
  948. }];
  949. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  950. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  951. arrayContainsAny:@[ @3 ]]
  952. ]];
  953. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  954. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  955. FIRFilter *filter2 = [FIRFilter andFilterWithFilters:@[
  956. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  957. arrayContains:@7]
  958. ]];
  959. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2] matchesResult:@[ @"doc3" ]];
  960. FIRFilter *filter3 = [FIRFilter orFilterWithFilters:@[
  961. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter andFilterWithFilters:@[
  962. [FIRFilter filterWhereField:@"b" arrayContains:@3], [FIRFilter filterWhereField:@"a"
  963. isEqualTo:@1]
  964. ]]
  965. ]];
  966. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter3]
  967. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  968. FIRFilter *filter4 = [FIRFilter andFilterWithFilters:@[
  969. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter orFilterWithFilters:@[
  970. [FIRFilter filterWhereField:@"b" arrayContains:@7], [FIRFilter filterWhereField:@"a"
  971. isEqualTo:@1]
  972. ]]
  973. ]];
  974. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter4] matchesResult:@[ @"doc3" ]];
  975. }
  976. - (void)testOrderByEquality {
  977. // TODO(orquery): Enable this test against production when possible.
  978. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  979. "Skip this test if running against production because order-by-equality is not "
  980. "supported yet.");
  981. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  982. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  983. @"doc2" : @{@"b" : @[ @1 ]},
  984. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ], @"c" : @10},
  985. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  986. @"doc5" : @{@"a" : @1},
  987. @"doc6" : @{@"a" : @2, @"c" : @20}
  988. }];
  989. [self checkOnlineAndOfflineQuery:[[collRef queryWhereFilter:[FIRFilter filterWhereField:@"a"
  990. isEqualTo:@1]]
  991. queryOrderedByField:@"a"]
  992. matchesResult:@[ @"doc1", @"doc4", @"doc5" ]];
  993. [self checkOnlineAndOfflineQuery:[[collRef
  994. queryWhereFilter:[FIRFilter filterWhereField:@"a"
  995. in:@[ @2, @3 ]]]
  996. queryOrderedByField:@"a"]
  997. matchesResult:@[ @"doc6", @"doc3" ]];
  998. }
  999. // Multiple Inequality
  1000. - (void)testMultipleInequalityOnDifferentFields {
  1001. // TODO(MIEQ): Enable this test against production when possible.
  1002. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1003. "Skip this test if running against production because multiple inequality is "
  1004. "not supported yet.");
  1005. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1006. @"doc1" : @{@"key" : @"a", @"sort" : @0, @"v" : @0},
  1007. @"doc2" : @{@"key" : @"b", @"sort" : @3, @"v" : @1},
  1008. @"doc3" : @{@"key" : @"c", @"sort" : @1, @"v" : @3},
  1009. @"doc4" : @{@"key" : @"d", @"sort" : @2, @"v" : @2}
  1010. }];
  1011. // Multiple inequality fields
  1012. FIRQuerySnapshot *snapshot = [self
  1013. readDocumentSetForRef:[[[collRef queryWhereField:@"key" isNotEqualTo:@"a"]
  1014. queryWhereField:@"sort"
  1015. isLessThanOrEqualTo:@2] queryWhereField:@"v" isGreaterThan:@2]];
  1016. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc3" ]));
  1017. // Duplicate inequality fields
  1018. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereField:@"key" isNotEqualTo:@"a"]
  1019. queryWhereField:@"sort"
  1020. isLessThanOrEqualTo:@2] queryWhereField:@"sort"
  1021. isGreaterThan:@1]];
  1022. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc4" ]));
  1023. // With multiple IN
  1024. snapshot = [self
  1025. readDocumentSetForRef:[[[[collRef queryWhereField:@"key"
  1026. isGreaterThanOrEqualTo:@"a"] queryWhereField:@"sort"
  1027. isLessThanOrEqualTo:@2]
  1028. queryWhereField:@"v"
  1029. in:@[ @2, @3, @4 ]] queryWhereField:@"sort"
  1030. in:@[ @2, @3 ]]];
  1031. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc4" ]));
  1032. // With NOT-IN
  1033. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereField:@"key"
  1034. isGreaterThanOrEqualTo:@"a"] queryWhereField:@"sort"
  1035. isLessThanOrEqualTo:@2]
  1036. queryWhereField:@"v"
  1037. notIn:@[ @2, @4, @5 ]]];
  1038. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc1", @"doc3" ]));
  1039. // With orderby
  1040. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereField:@"key"
  1041. isGreaterThanOrEqualTo:@"a"] queryWhereField:@"sort"
  1042. isLessThanOrEqualTo:@2]
  1043. queryOrderedByField:@"v"
  1044. descending:YES]];
  1045. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc3", @"doc4", @"doc1" ]));
  1046. // With limit
  1047. snapshot = [self readDocumentSetForRef:[[[[collRef queryWhereField:@"key"
  1048. isGreaterThanOrEqualTo:@"a"] queryWhereField:@"sort"
  1049. isLessThanOrEqualTo:@2]
  1050. queryOrderedByField:@"v"
  1051. descending:YES] queryLimitedTo:2]];
  1052. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc3", @"doc4" ]));
  1053. // With limitedToLast
  1054. snapshot = [self readDocumentSetForRef:[[[[collRef queryWhereField:@"key"
  1055. isGreaterThanOrEqualTo:@"a"] queryWhereField:@"sort"
  1056. isLessThanOrEqualTo:@2]
  1057. queryOrderedByField:@"v"
  1058. descending:YES] queryLimitedToLast:2]];
  1059. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc4", @"doc1" ]));
  1060. }
  1061. - (void)testMultipleInequalityOnSpecialValues {
  1062. // TODO(MIEQ): Enable this test against production when possible.
  1063. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1064. "Skip this test if running against production because multiple inequality is "
  1065. "not supported yet.");
  1066. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1067. @"doc1" : @{@"key" : @"a", @"sort" : @0, @"v" : @0},
  1068. @"doc2" : @{@"key" : @"b", @"sort" : @(NAN), @"v" : @1},
  1069. @"doc3" : @{@"key" : @"c", @"sort" : [NSNull null], @"v" : @3},
  1070. @"doc4" : @{@"key" : @"d", @"v" : @0},
  1071. @"doc5" : @{@"key" : @"e", @"sort" : @1},
  1072. @"doc6" : @{@"key" : @"f", @"sort" : @1, @"v" : @1}
  1073. }];
  1074. FIRQuerySnapshot *snapshot =
  1075. [self readDocumentSetForRef:[[collRef queryWhereField:@"key"
  1076. isNotEqualTo:@"a"] queryWhereField:@"sort"
  1077. isLessThanOrEqualTo:@2]];
  1078. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc5", @"doc6" ]));
  1079. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereField:@"key" isNotEqualTo:@"a"]
  1080. queryWhereField:@"sort"
  1081. isLessThanOrEqualTo:@2] queryWhereField:@"v"
  1082. isLessThanOrEqualTo:@1]];
  1083. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc6" ]));
  1084. }
  1085. - (void)testMultipleInequalityWithArrayMembership {
  1086. // TODO(MIEQ): Enable this test against production when possible.
  1087. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1088. "Skip this test if running against production because multiple inequality is "
  1089. "not supported yet.");
  1090. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1091. @"doc1" : @{@"key" : @"a", @"sort" : @0, @"v" : @[ @0 ]},
  1092. @"doc2" : @{@"key" : @"b", @"sort" : @1, @"v" : @[ @0, @1, @3 ]},
  1093. @"doc3" : @{@"key" : @"c", @"sort" : @1, @"v" : @[]},
  1094. @"doc4" : @{@"key" : @"d", @"sort" : @2, @"v" : @[ @1 ]},
  1095. @"doc5" : @{@"key" : @"e", @"sort" : @3, @"v" : @[ @2, @4 ]},
  1096. @"doc6" : @{@"key" : @"f", @"sort" : @4, @"v" : @[ @(NAN) ]},
  1097. @"doc7" : @{@"key" : @"g", @"sort" : @4, @"v" : @[ [NSNull null] ]}
  1098. }];
  1099. FIRQuerySnapshot *snapshot = [self
  1100. readDocumentSetForRef:[[[collRef queryWhereField:@"key" isNotEqualTo:@"a"]
  1101. queryWhereField:@"sort"
  1102. isGreaterThanOrEqualTo:@1] queryWhereField:@"v" arrayContains:@0]];
  1103. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc2" ]));
  1104. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereField:@"key"
  1105. isNotEqualTo:@"a"] queryWhereField:@"sort"
  1106. isGreaterThanOrEqualTo:@1]
  1107. queryWhereField:@"v"
  1108. arrayContainsAny:@[ @0, @1 ]]];
  1109. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc2", @"doc4" ]));
  1110. }
  1111. - (NSDictionary<NSString *, id> *)nestedData:(int)number {
  1112. return @{
  1113. @"name" : [NSString stringWithFormat:@"room %d", number],
  1114. @"metadata" : @{@"createdAt" : @(number)},
  1115. @"field" : [NSString stringWithFormat:@"field %d", number],
  1116. @"field.dot" : @(number),
  1117. @"field\\slash" : @(number)
  1118. };
  1119. }
  1120. - (void)testMultipleInequalityWithNestedField {
  1121. // TODO(MIEQ): Enable this test against production when possible.
  1122. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1123. "Skip this test if running against production because multiple inequality is "
  1124. "not supported yet.");
  1125. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1126. @"doc1" : [self nestedData:400],
  1127. @"doc2" : [self nestedData:200],
  1128. @"doc3" : [self nestedData:100],
  1129. @"doc4" : [self nestedData:300]
  1130. }];
  1131. FIRQuerySnapshot *snapshot = [self
  1132. readDocumentSetForRef:[[[[collRef queryWhereField:@"metadata.createdAt"
  1133. isLessThanOrEqualTo:@500] queryWhereField:@"metadata.createdAt"
  1134. isGreaterThan:@100]
  1135. queryWhereField:@"name"
  1136. isNotEqualTo:@"room 200"] queryOrderedByField:@"name"
  1137. descending:NO]];
  1138. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc4", @"doc1" ]));
  1139. snapshot =
  1140. [self readDocumentSetForRef:[[[[collRef queryWhereField:@"field"
  1141. isGreaterThanOrEqualTo:@"field 100"]
  1142. queryWhereFieldPath:[[FIRFieldPath alloc]
  1143. initWithFields:@[ @"field.dot" ]]
  1144. isNotEqualTo:@300] queryWhereField:@"field\\slash"
  1145. isLessThan:@400]
  1146. queryOrderedByField:@"name"
  1147. descending:YES]];
  1148. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc2", @"doc3" ]));
  1149. }
  1150. - (void)testMultipleInequalityWithCompositeFilters {
  1151. // TODO(MIEQ): Enable this test against production when possible.
  1152. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1153. "Skip this test if running against production because multiple inequality is "
  1154. "not supported yet.");
  1155. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1156. @"doc1" : @{@"key" : @"a", @"sort" : @0, @"v" : @5},
  1157. @"doc2" : @{@"key" : @"aa", @"sort" : @4, @"v" : @4},
  1158. @"doc3" : @{@"key" : @"c", @"sort" : @3, @"v" : @3},
  1159. @"doc4" : @{@"key" : @"b", @"sort" : @2, @"v" : @2},
  1160. @"doc5" : @{@"key" : @"b", @"sort" : @2, @"v" : @1},
  1161. @"doc6" : @{@"key" : @"b", @"sort" : @0, @"v" : @0}
  1162. }];
  1163. FIRQuerySnapshot *snapshot = [self
  1164. readDocumentSetForRef:[collRef queryWhereFilter:[FIRFilter orFilterWithFilters:@[
  1165. [FIRFilter andFilterWithFilters:@[
  1166. [FIRFilter filterWhereField:@"key" isEqualTo:@"b"],
  1167. [FIRFilter filterWhereField:@"sort" isLessThanOrEqualTo:@2]
  1168. ]],
  1169. [FIRFilter andFilterWithFilters:@[
  1170. [FIRFilter filterWhereField:@"key" isNotEqualTo:@"b"],
  1171. [FIRFilter filterWhereField:@"v" isGreaterThan:@4]
  1172. ]]
  1173. ]]]];
  1174. // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc
  1175. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1176. (@[ @"doc1", @"doc6", @"doc5", @"doc4" ]));
  1177. snapshot = [self
  1178. readDocumentSetForRef:[[[collRef queryWhereFilter:[FIRFilter orFilterWithFilters:@[
  1179. [FIRFilter andFilterWithFilters:@[
  1180. [FIRFilter filterWhereField:@"key" isEqualTo:@"b"],
  1181. [FIRFilter filterWhereField:@"sort"
  1182. isLessThanOrEqualTo:@2]
  1183. ]],
  1184. [FIRFilter andFilterWithFilters:@[
  1185. [FIRFilter filterWhereField:@"key" isNotEqualTo:@"b"],
  1186. [FIRFilter filterWhereField:@"v" isGreaterThan:@4]
  1187. ]]
  1188. ]]] queryOrderedByField:@"sort"
  1189. descending:YES] queryOrderedByField:@"key"]];
  1190. // Ordered by: 'sort' desc, 'key' asc, 'v' asc, __name__ asc
  1191. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1192. (@[ @"doc5", @"doc4", @"doc1", @"doc6" ]));
  1193. snapshot = [self
  1194. readDocumentSetForRef:[collRef
  1195. queryWhereFilter:[FIRFilter andFilterWithFilters:@[
  1196. [FIRFilter orFilterWithFilters:@[
  1197. [FIRFilter andFilterWithFilters:@[
  1198. [FIRFilter filterWhereField:@"key" isEqualTo:@"b"],
  1199. [FIRFilter filterWhereField:@"sort" isLessThanOrEqualTo:@4]
  1200. ]],
  1201. [FIRFilter andFilterWithFilters:@[
  1202. [FIRFilter filterWhereField:@"key" isNotEqualTo:@"b"],
  1203. [FIRFilter filterWhereField:@"v" isGreaterThanOrEqualTo:@4]
  1204. ]]
  1205. ]],
  1206. [FIRFilter orFilterWithFilters:@[
  1207. [FIRFilter andFilterWithFilters:@[
  1208. [FIRFilter filterWhereField:@"key" isGreaterThan:@"b"],
  1209. [FIRFilter filterWhereField:@"sort" isGreaterThanOrEqualTo:@1]
  1210. ]],
  1211. [FIRFilter andFilterWithFilters:@[
  1212. [FIRFilter filterWhereField:@"key" isLessThan:@"b"],
  1213. [FIRFilter filterWhereField:@"v" isGreaterThan:@0]
  1214. ]]
  1215. ]]
  1216. ]]]];
  1217. // Implicitly ordered by: 'key' asc, 'sort' asc, 'v' asc, __name__ asc
  1218. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc1", @"doc2" ]));
  1219. }
  1220. - (void)testMultipleInequalityFieldsWillBeImplicitlyOrderedLexicographically {
  1221. // TODO(MIEQ): Enable this test against production when possible.
  1222. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1223. "Skip this test if running against production because multiple inequality is "
  1224. "not supported yet.");
  1225. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1226. @"doc1" : @{@"key" : @"a", @"sort" : @0, @"v" : @5},
  1227. @"doc2" : @{@"key" : @"aa", @"sort" : @4, @"v" : @4},
  1228. @"doc3" : @{@"key" : @"b", @"sort" : @3, @"v" : @3},
  1229. @"doc4" : @{@"key" : @"b", @"sort" : @2, @"v" : @2},
  1230. @"doc5" : @{@"key" : @"b", @"sort" : @2, @"v" : @1},
  1231. @"doc6" : @{@"key" : @"b", @"sort" : @0, @"v" : @0}
  1232. }];
  1233. FIRQuerySnapshot *snapshot = [self
  1234. readDocumentSetForRef:[[[collRef queryWhereField:@"key" isNotEqualTo:@"a"]
  1235. queryWhereField:@"sort"
  1236. isGreaterThan:@1] queryWhereField:@"v" in:@[ @1, @2, @3, @4 ]]];
  1237. // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc
  1238. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1239. (@[ @"doc2", @"doc4", @"doc5", @"doc3" ]));
  1240. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereField:@"sort"
  1241. isGreaterThan:@1] queryWhereField:@"key"
  1242. isNotEqualTo:@"a"]
  1243. queryWhereField:@"v"
  1244. in:@[ @1, @2, @3, @4 ]]];
  1245. // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc
  1246. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1247. (@[ @"doc2", @"doc4", @"doc5", @"doc3" ]));
  1248. }
  1249. - (void)testMultipleInequalityWithMultipleExplicitOrderBy {
  1250. // TODO(MIEQ): Enable this test against production when possible.
  1251. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1252. "Skip this test if running against production because multiple inequality is "
  1253. "not supported yet.");
  1254. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1255. @"doc1" : @{@"key" : @"a", @"sort" : @5, @"v" : @0},
  1256. @"doc2" : @{@"key" : @"aa", @"sort" : @4, @"v" : @0},
  1257. @"doc3" : @{@"key" : @"b", @"sort" : @3, @"v" : @1},
  1258. @"doc4" : @{@"key" : @"b", @"sort" : @2, @"v" : @1},
  1259. @"doc5" : @{@"key" : @"bb", @"sort" : @1, @"v" : @1},
  1260. @"doc6" : @{@"key" : @"c", @"sort" : @0, @"v" : @2}
  1261. }];
  1262. FIRQuerySnapshot *snapshot = [self
  1263. readDocumentSetForRef:[[[collRef queryWhereField:@"key" isGreaterThan:@"a"]
  1264. queryWhereField:@"sort"
  1265. isGreaterThanOrEqualTo:@1] queryOrderedByField:@"v" descending:NO]];
  1266. // Ordered by: 'v' asc, 'key' asc, 'sort' asc, __name__ asc
  1267. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1268. (@[ @"doc2", @"doc4", @"doc3", @"doc5" ]));
  1269. snapshot = [self readDocumentSetForRef:[[[[collRef queryWhereField:@"key"
  1270. isGreaterThan:@"a"] queryWhereField:@"sort"
  1271. isGreaterThanOrEqualTo:@1]
  1272. queryOrderedByField:@"v"
  1273. descending:NO] queryOrderedByField:@"sort"
  1274. descending:NO]];
  1275. // Ordered by: 'v asc, 'sort' asc, 'key' asc, __name__ asc
  1276. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1277. (@[ @"doc2", @"doc5", @"doc4", @"doc3" ]));
  1278. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereField:@"key" isGreaterThan:@"a"]
  1279. queryWhereField:@"sort"
  1280. isGreaterThanOrEqualTo:@1] queryOrderedByField:@"v"
  1281. descending:YES]];
  1282. // Implicit order by matches the direction of last explicit order by.
  1283. // Ordered by: 'v' desc, 'key' desc, 'sort' desc, __name__ desc
  1284. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1285. (@[ @"doc5", @"doc3", @"doc4", @"doc2" ]));
  1286. snapshot = [self readDocumentSetForRef:[[[[collRef queryWhereField:@"key"
  1287. isGreaterThan:@"a"] queryWhereField:@"sort"
  1288. isGreaterThanOrEqualTo:@1]
  1289. queryOrderedByField:@"v"
  1290. descending:YES] queryOrderedByField:@"sort"
  1291. descending:NO]];
  1292. // Ordered by: 'v desc, 'sort' asc, 'key' asc, __name__ asc
  1293. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot),
  1294. (@[ @"doc5", @"doc4", @"doc3", @"doc2" ]));
  1295. }
  1296. - (void)testMultipleInequalityInAggregateQuery {
  1297. // TODO(MIEQ): Enable this test against production when possible.
  1298. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1299. "Skip this test if running against production because multiple inequality is "
  1300. "not supported yet.");
  1301. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1302. @"doc1" : @{@"key" : @"a", @"sort" : @5, @"v" : @0},
  1303. @"doc2" : @{@"key" : @"aa", @"sort" : @4, @"v" : @0},
  1304. @"doc3" : @{@"key" : @"b", @"sort" : @3, @"v" : @1},
  1305. @"doc4" : @{@"key" : @"b", @"sort" : @2, @"v" : @1},
  1306. @"doc5" : @{@"key" : @"bb", @"sort" : @1, @"v" : @1},
  1307. }];
  1308. FIRAggregateQuerySnapshot *snapshot =
  1309. [self readSnapshotForAggregate:[[[[collRef queryWhereField:@"key" isGreaterThan:@"a"]
  1310. queryWhereField:@"sort"
  1311. isGreaterThanOrEqualTo:@1] queryOrderedByField:@"v"
  1312. descending:NO]
  1313. aggregate:@[
  1314. [FIRAggregateField aggregateFieldForCount],
  1315. [FIRAggregateField aggregateFieldForSumOfField:@"sort"],
  1316. [FIRAggregateField aggregateFieldForAverageOfField:@"v"]
  1317. ]]];
  1318. XCTAssertEqual([snapshot count], [NSNumber numberWithLong:4L]);
  1319. snapshot = [self
  1320. readSnapshotForAggregate:[[[[collRef queryWhereField:@"key" isGreaterThan:@"a"]
  1321. queryWhereField:@"sort"
  1322. isGreaterThanOrEqualTo:@1] queryWhereField:@"v" isNotEqualTo:@0]
  1323. aggregate:@[
  1324. [FIRAggregateField aggregateFieldForCount],
  1325. [FIRAggregateField aggregateFieldForSumOfField:@"sort"],
  1326. [FIRAggregateField aggregateFieldForAverageOfField:@"v"],
  1327. ]]];
  1328. XCTAssertEqual([snapshot valueForAggregation:[FIRAggregateField aggregateFieldForCount]],
  1329. [NSNumber numberWithLong:3L]);
  1330. XCTAssertEqual(
  1331. [[snapshot valueForAggregation:[FIRAggregateField aggregateFieldForSumOfField:@"sort"]]
  1332. longValue],
  1333. 6L);
  1334. XCTAssertEqual(
  1335. [snapshot valueForAggregation:[FIRAggregateField aggregateFieldForAverageOfField:@"v"]],
  1336. [NSNumber numberWithDouble:1.0]);
  1337. }
  1338. - (void)testMultipleInequalityFieldsWithDocumentKey {
  1339. // TODO(MIEQ): Enable this test against production when possible.
  1340. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1341. "Skip this test if running against production because multiple inequality is "
  1342. "not supported yet.");
  1343. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1344. @"doc1" : @{@"key" : @"a", @"sort" : @5},
  1345. @"doc2" : @{@"key" : @"aa", @"sort" : @4},
  1346. @"doc3" : @{@"key" : @"b", @"sort" : @3},
  1347. @"doc4" : @{@"key" : @"b", @"sort" : @2},
  1348. @"doc5" : @{@"key" : @"bb", @"sort" : @1}
  1349. }];
  1350. FIRQuerySnapshot *snapshot = [self
  1351. readDocumentSetForRef:[[[collRef queryWhereField:@"sort"
  1352. isGreaterThan:@1] queryWhereField:@"key" isNotEqualTo:@"a"]
  1353. queryWhereFieldPath:[FIRFieldPath documentID]
  1354. isLessThan:@"doc5"]];
  1355. // Document Key in inequality field will implicitly ordered to the last.
  1356. // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc
  1357. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc2", @"doc4", @"doc3" ]));
  1358. snapshot = [self readDocumentSetForRef:[[[collRef queryWhereFieldPath:[FIRFieldPath documentID]
  1359. isLessThan:@"doc5"]
  1360. queryWhereField:@"sort"
  1361. isGreaterThan:@1] queryWhereField:@"key"
  1362. isNotEqualTo:@"a"]];
  1363. // Changing filters order will not effect implicit order.
  1364. // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc
  1365. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc2", @"doc4", @"doc3" ]));
  1366. snapshot = [self
  1367. readDocumentSetForRef:[[[[collRef queryWhereFieldPath:[FIRFieldPath documentID]
  1368. isLessThan:@"doc5"] queryWhereField:@"sort"
  1369. isGreaterThan:@1]
  1370. queryWhereField:@"key"
  1371. isNotEqualTo:@"a"] queryOrderedByField:@"sort" descending:YES]];
  1372. // Ordered by: 'sort' desc,'key' desc, __name__ desc
  1373. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc2", @"doc3", @"doc4" ]));
  1374. }
  1375. - (void)testMultipleInequalityReadFromCacheWhenOffline {
  1376. // TODO(MIEQ): Enable this test against production when possible.
  1377. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1378. "Skip this test if running against production because multiple inequality is "
  1379. "not supported yet.");
  1380. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1381. @"doc1" : @{@"key" : @"a", @"sort" : @1},
  1382. @"doc2" : @{@"key" : @"aa", @"sort" : @4},
  1383. @"doc3" : @{@"key" : @"b", @"sort" : @3},
  1384. @"doc4" : @{@"key" : @"b", @"sort" : @2},
  1385. }];
  1386. FIRQuery *query = [[collRef queryWhereField:@"key" isNotEqualTo:@"a"] queryWhereField:@"sort"
  1387. isLessThanOrEqualTo:@3];
  1388. // populate the cache.
  1389. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:query];
  1390. XCTAssertEqual(snapshot.count, 2L);
  1391. XCTAssertEqual(snapshot.metadata.isFromCache, NO);
  1392. [self disableNetwork];
  1393. snapshot = [self readDocumentSetForRef:query];
  1394. XCTAssertEqual(snapshot.count, 2L);
  1395. XCTAssertEqual(snapshot.metadata.isFromCache, YES);
  1396. // Implicitly ordered by: 'key' asc, 'sort' asc, __name__ asc
  1397. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"doc4", @"doc3" ]));
  1398. }
  1399. - (void)testMultipleInequalityFromCacheAndFromServer {
  1400. // TODO(MIEQ): Enable this test against production when possible.
  1401. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  1402. "Skip this test if running against production because multiple inequality is "
  1403. "not supported yet.");
  1404. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  1405. @"doc1" : @{@"a" : @1, @"b" : @0},
  1406. @"doc2" : @{@"a" : @2, @"b" : @1},
  1407. @"doc3" : @{@"a" : @3, @"b" : @2},
  1408. @"doc4" : @{@"a" : @1, @"b" : @3},
  1409. @"doc5" : @{@"a" : @1, @"b" : @1},
  1410. }];
  1411. // implicit AND: a != 1 && b < 2
  1412. FIRQuery *query = [[collRef queryWhereField:@"a" isNotEqualTo:@1] queryWhereField:@"b"
  1413. isLessThan:@2];
  1414. [self checkOnlineAndOfflineQuery:query matchesResult:@[ @"doc2" ]];
  1415. // explicit AND: a != 1 && b < 2
  1416. FIRFilter *filter = [FIRFilter andFilterWithFilters:@[
  1417. [FIRFilter filterWhereField:@"a" isNotEqualTo:@1], [FIRFilter filterWhereField:@"b"
  1418. isLessThan:@2]
  1419. ]];
  1420. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter] matchesResult:@[ @"doc2" ]];
  1421. // explicit AND: a < 3 && b not-in [2, 3]
  1422. // Implicitly ordered by: a asc, b asc, __name__ asc
  1423. filter = [FIRFilter andFilterWithFilters:@[
  1424. [FIRFilter filterWhereField:@"a" isLessThan:@3], [FIRFilter filterWhereField:@"b"
  1425. notIn:@[ @2, @3 ]]
  1426. ]];
  1427. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter]
  1428. matchesResult:@[ @"doc1", @"doc5", @"doc2" ]];
  1429. // a <3 && b != 0, ordered by: b desc, a desc, __name__ desc
  1430. query = [[[[collRef queryWhereField:@"a" isLessThan:@3] queryWhereField:@"b" isNotEqualTo:@0]
  1431. queryOrderedByField:@"b"
  1432. descending:YES] queryLimitedTo:2];
  1433. [self checkOnlineAndOfflineQuery:query matchesResult:@[ @"doc4", @"doc2" ]];
  1434. // explicit OR: a>2 || b<1.
  1435. filter = [FIRFilter orFilterWithFilters:@[
  1436. [FIRFilter filterWhereField:@"a" isGreaterThan:@2], [FIRFilter filterWhereField:@"b"
  1437. isLessThan:@1]
  1438. ]];
  1439. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter]
  1440. matchesResult:@[ @"doc1", @"doc3" ]];
  1441. }
  1442. - (void)testResumingAQueryShouldUseBloomFilterToAvoidFullRequery {
  1443. // TODO(b/291365820): Stop skipping this test when running against the Firestore emulator once
  1444. // the emulator is improved to include a bloom filter in the existence filter messages that it
  1445. // sends.
  1446. XCTSkipIf([FSTIntegrationTestCase isRunningAgainstEmulator],
  1447. "Skip this test when running against the Firestore emulator because the emulator does "
  1448. "not include a bloom filter when it sends existence filter messages, making it "
  1449. "impossible for this test to verify the correctness of the bloom filter.");
  1450. // Set this test to stop when the first failure occurs because some test assertion failures make
  1451. // the rest of the test not applicable or will even crash.
  1452. [self setContinueAfterFailure:NO];
  1453. // Prepare the names and contents of the 100 documents to create.
  1454. NSMutableDictionary<NSString *, NSDictionary<NSString *, id> *> *testDocs =
  1455. [[NSMutableDictionary alloc] init];
  1456. for (int i = 0; i < 100; i++) {
  1457. [testDocs setValue:@{@"key" : @42} forKey:[NSString stringWithFormat:@"doc%@", @(1000 + i)]];
  1458. }
  1459. // Each iteration of the "while" loop below runs a single iteration of the test. The test will
  1460. // be run multiple times only if a bloom filter false positive occurs.
  1461. int attemptNumber = 0;
  1462. while (true) {
  1463. attemptNumber++;
  1464. // Create 100 documents in a new collection.
  1465. FIRCollectionReference *collRef = [self collectionRefWithDocuments:testDocs];
  1466. // Run a query to populate the local cache with the 100 documents and a resume token.
  1467. FIRQuerySnapshot *querySnapshot1 = [self readDocumentSetForRef:collRef
  1468. source:FIRFirestoreSourceDefault];
  1469. XCTAssertEqual(querySnapshot1.count, 100, @"querySnapshot1.count has an unexpected value");
  1470. NSArray<FIRDocumentReference *> *createdDocuments =
  1471. FIRDocumentReferenceArrayFromQuerySnapshot(querySnapshot1);
  1472. // Delete 50 of the 100 documents. Use a different Firestore instance to avoid affecting the
  1473. // local cache.
  1474. NSSet<NSString *> *deletedDocumentIds;
  1475. {
  1476. FIRFirestore *db2 = [self firestore];
  1477. FIRWriteBatch *batch = [db2 batch];
  1478. NSMutableArray<NSString *> *deletedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1479. for (decltype(createdDocuments.count) i = 0; i < createdDocuments.count; i += 2) {
  1480. FIRDocumentReference *documentToDelete = [db2 documentWithPath:createdDocuments[i].path];
  1481. [batch deleteDocument:documentToDelete];
  1482. [deletedDocumentIdsAccumulator addObject:documentToDelete.documentID];
  1483. }
  1484. [self commitWriteBatch:batch];
  1485. deletedDocumentIds = [NSSet setWithArray:deletedDocumentIdsAccumulator];
  1486. }
  1487. XCTAssertEqual(deletedDocumentIds.count, 50u, @"deletedDocumentIds has the wrong size");
  1488. // Wait for 10 seconds, during which Watch will stop tracking the query and will send an
  1489. // existence filter rather than "delete" events when the query is resumed.
  1490. [NSThread sleepForTimeInterval:10.0f];
  1491. // Resume the query and save the resulting snapshot for verification.
  1492. // Use some internal testing hooks to "capture" the existence filter mismatches to verify that
  1493. // Watch sent a bloom filter, and it was used to avert a full requery.
  1494. __block FIRQuerySnapshot *querySnapshot2;
  1495. NSArray<FSTTestingHooksExistenceFilterMismatchInfo *> *existenceFilterMismatches =
  1496. [FSTTestingHooks captureExistenceFilterMismatchesDuringBlock:^{
  1497. querySnapshot2 = [self readDocumentSetForRef:collRef source:FIRFirestoreSourceDefault];
  1498. }];
  1499. // Verify that the snapshot from the resumed query contains the expected documents; that is,
  1500. // that it contains the 50 documents that were _not_ deleted.
  1501. {
  1502. NSMutableArray<NSString *> *expectedDocumentIds = [[NSMutableArray alloc] init];
  1503. for (FIRDocumentReference *documentRef in createdDocuments) {
  1504. if (![deletedDocumentIds containsObject:documentRef.documentID]) {
  1505. [expectedDocumentIds addObject:documentRef.documentID];
  1506. }
  1507. }
  1508. XCTAssertEqualObjects([NSSet setWithArray:FIRQuerySnapshotGetIDs(querySnapshot2)],
  1509. [NSSet setWithArray:expectedDocumentIds],
  1510. @"querySnapshot2 has the wrong documents");
  1511. }
  1512. // Verify that Watch sent an existence filter with the correct counts when the query was
  1513. // resumed.
  1514. XCTAssertEqual(existenceFilterMismatches.count, 1u,
  1515. @"Watch should have sent exactly 1 existence filter");
  1516. FSTTestingHooksExistenceFilterMismatchInfo *existenceFilterMismatchInfo =
  1517. existenceFilterMismatches[0];
  1518. XCTAssertEqual(existenceFilterMismatchInfo.localCacheCount, 100);
  1519. XCTAssertEqual(existenceFilterMismatchInfo.existenceFilterCount, 50);
  1520. // Verify that Watch sent a valid bloom filter.
  1521. FSTTestingHooksBloomFilter *bloomFilter = existenceFilterMismatchInfo.bloomFilter;
  1522. XCTAssertNotNil(bloomFilter,
  1523. "Watch should have included a bloom filter in the existence filter");
  1524. XCTAssertGreaterThan(bloomFilter.hashCount, 0);
  1525. XCTAssertGreaterThan(bloomFilter.bitmapLength, 0);
  1526. XCTAssertGreaterThan(bloomFilter.padding, 0);
  1527. XCTAssertLessThan(bloomFilter.padding, 8);
  1528. // Verify that the bloom filter was successfully used to avert a full requery. If a false
  1529. // positive occurred then retry the entire test. Although statistically rare, false positives
  1530. // are expected to happen occasionally. When a false positive _does_ happen, just retry the test
  1531. // with a different set of documents. If that retry _also_ experiences a false positive, then
  1532. // fail the test because that is so improbable that something must have gone wrong.
  1533. if (attemptNumber == 1 && !bloomFilter.applied) {
  1534. continue;
  1535. }
  1536. XCTAssertTrue(bloomFilter.applied,
  1537. @"The bloom filter should have been successfully applied with attemptNumber=%@",
  1538. @(attemptNumber));
  1539. // Break out of the test loop now that the test passes.
  1540. break;
  1541. }
  1542. }
  1543. - (void)
  1544. testBloomFilterShouldAvertAFullRequeryWhenDocumentsWereAddedDeletedRemovedUpdatedAndUnchangedSinceTheResumeToken {
  1545. // TODO(b/291365820): Stop skipping this test when running against the Firestore emulator once
  1546. // the emulator is improved to include a bloom filter in the existence filter messages that it
  1547. // sends.
  1548. XCTSkipIf([FSTIntegrationTestCase isRunningAgainstEmulator],
  1549. "Skip this test when running against the Firestore emulator because the emulator does "
  1550. "not include a bloom filter when it sends existence filter messages, making it "
  1551. "impossible for this test to verify the correctness of the bloom filter.");
  1552. // Set this test to stop when the first failure occurs because some test assertion failures make
  1553. // the rest of the test not applicable or will even crash.
  1554. [self setContinueAfterFailure:NO];
  1555. // Prepare the names and contents of the 20 documents to create.
  1556. NSMutableDictionary<NSString *, NSDictionary<NSString *, id> *> *testDocs =
  1557. [[NSMutableDictionary alloc] init];
  1558. for (int i = 0; i < 20; i++) {
  1559. [testDocs setValue:@{@"key" : @42, @"removed" : @NO}
  1560. forKey:[NSString stringWithFormat:@"doc%@", @(1000 + i)]];
  1561. }
  1562. // Each iteration of the "while" loop below runs a single iteration of the test. The test will
  1563. // be run multiple times only if a bloom filter false positive occurs.
  1564. int attemptNumber = 0;
  1565. while (true) {
  1566. attemptNumber++;
  1567. // Create 20 documents in a new collection.
  1568. FIRCollectionReference *collRef = [self collectionRefWithDocuments:testDocs];
  1569. FIRQuery *query = [collRef queryWhereField:@"removed" isEqualTo:@NO];
  1570. // Run a query to populate the local cache with the 20 documents and a resume token.
  1571. FIRQuerySnapshot *querySnapshot1 = [self readDocumentSetForRef:query
  1572. source:FIRFirestoreSourceDefault];
  1573. XCTAssertEqual(querySnapshot1.count, 20u, @"querySnapshot1.count has an unexpected value");
  1574. NSArray<FIRDocumentReference *> *createdDocuments =
  1575. FIRDocumentReferenceArrayFromQuerySnapshot(querySnapshot1);
  1576. // Out of the 20 existing documents, leave 5 docs untouched, delete 5 docs, remove 5 docs,
  1577. // update 5 docs, and add 15 new docs.
  1578. NSSet<NSString *> *deletedDocumentIds;
  1579. NSSet<NSString *> *removedDocumentIds;
  1580. NSSet<NSString *> *updatedDocumentIds;
  1581. NSMutableArray<NSString *> *addedDocumentIds = [[NSMutableArray alloc] init];
  1582. {
  1583. FIRFirestore *db2 = [self firestore];
  1584. FIRWriteBatch *batch = [db2 batch];
  1585. NSMutableArray<NSString *> *deletedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1586. for (decltype(createdDocuments.count) i = 0; i < createdDocuments.count; i += 4) {
  1587. FIRDocumentReference *documentToDelete = [db2 documentWithPath:createdDocuments[i].path];
  1588. [batch deleteDocument:documentToDelete];
  1589. [deletedDocumentIdsAccumulator addObject:documentToDelete.documentID];
  1590. }
  1591. deletedDocumentIds = [NSSet setWithArray:deletedDocumentIdsAccumulator];
  1592. XCTAssertEqual(deletedDocumentIds.count, 5u, @"deletedDocumentIds has the wrong size");
  1593. // Update 5 documents to no longer match the query.
  1594. NSMutableArray<NSString *> *removedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1595. for (decltype(createdDocuments.count) i = 1; i < createdDocuments.count; i += 4) {
  1596. FIRDocumentReference *documentToRemove = [db2 documentWithPath:createdDocuments[i].path];
  1597. [batch updateData:@{@"removed" : @YES} forDocument:documentToRemove];
  1598. [removedDocumentIdsAccumulator addObject:documentToRemove.documentID];
  1599. }
  1600. removedDocumentIds = [NSSet setWithArray:removedDocumentIdsAccumulator];
  1601. XCTAssertEqual(removedDocumentIds.count, 5u, @"removedDocumentIds has the wrong size");
  1602. // Update 5 documents, but ensure they still match the query.
  1603. NSMutableArray<NSString *> *updatedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1604. for (decltype(createdDocuments.count) i = 2; i < createdDocuments.count; i += 4) {
  1605. FIRDocumentReference *documentToUpdate = [db2 documentWithPath:createdDocuments[i].path];
  1606. [batch updateData:@{@"key" : @43} forDocument:documentToUpdate];
  1607. [updatedDocumentIdsAccumulator addObject:documentToUpdate.documentID];
  1608. }
  1609. updatedDocumentIds = [NSSet setWithArray:updatedDocumentIdsAccumulator];
  1610. XCTAssertEqual(updatedDocumentIds.count, 5u, @"updatedDocumentIds has the wrong size");
  1611. for (int i = 0; i < 15; i += 1) {
  1612. FIRDocumentReference *documentToAdd = [db2
  1613. documentWithPath:[NSString stringWithFormat:@"%@/newDoc%@", collRef.path, @(1000 + i)]];
  1614. [batch setData:@{@"key" : @42, @"removed" : @NO} forDocument:documentToAdd];
  1615. [addedDocumentIds addObject:documentToAdd.documentID];
  1616. }
  1617. // Ensure the documentIds above are mutually exclusive.
  1618. NSMutableSet<NSString *> *mergedSet = [NSMutableSet setWithArray:addedDocumentIds];
  1619. [mergedSet unionSet:deletedDocumentIds];
  1620. [mergedSet unionSet:removedDocumentIds];
  1621. [mergedSet unionSet:updatedDocumentIds];
  1622. XCTAssertEqual(mergedSet.count, 30u, @"There are documents experienced multiple operations.");
  1623. [self commitWriteBatch:batch];
  1624. }
  1625. // Wait for 10 seconds, during which Watch will stop tracking the query and will send an
  1626. // existence filter rather than "delete" events when the query is resumed.
  1627. [NSThread sleepForTimeInterval:10.0f];
  1628. // Resume the query and save the resulting snapshot for verification. Use some internal testing
  1629. // hooks to "capture" the existence filter mismatches to verify that Watch sent a bloom
  1630. // filter, and it was used to avert a full requery.
  1631. __block FIRQuerySnapshot *querySnapshot2;
  1632. NSArray<FSTTestingHooksExistenceFilterMismatchInfo *> *existenceFilterMismatches =
  1633. [FSTTestingHooks captureExistenceFilterMismatchesDuringBlock:^{
  1634. querySnapshot2 = [self readDocumentSetForRef:query source:FIRFirestoreSourceDefault];
  1635. }];
  1636. XCTAssertEqual(querySnapshot2.count, 25u, @"querySnapshot1.count has an unexpected value");
  1637. // Verify that the snapshot from the resumed query contains the expected documents; that is, 10
  1638. // existing documents that still match the query, and 15 documents that are newly added.
  1639. {
  1640. NSMutableArray<NSString *> *expectedDocumentIds = [[NSMutableArray alloc] init];
  1641. for (FIRDocumentReference *documentRef in createdDocuments) {
  1642. if (![deletedDocumentIds containsObject:documentRef.documentID] &&
  1643. ![removedDocumentIds containsObject:documentRef.documentID]) {
  1644. [expectedDocumentIds addObject:documentRef.documentID];
  1645. }
  1646. }
  1647. [expectedDocumentIds addObjectsFromArray:addedDocumentIds];
  1648. XCTAssertEqualObjects([NSSet setWithArray:FIRQuerySnapshotGetIDs(querySnapshot2)],
  1649. [NSSet setWithArray:expectedDocumentIds],
  1650. @"querySnapshot2 has the wrong documents");
  1651. }
  1652. // Verify that Watch sent an existence filter with the correct counts when the query was
  1653. // resumed.
  1654. XCTAssertEqual(existenceFilterMismatches.count, 1u,
  1655. @"Watch should have sent exactly 1 existence filter");
  1656. FSTTestingHooksExistenceFilterMismatchInfo *existenceFilterMismatchInfo =
  1657. existenceFilterMismatches[0];
  1658. XCTAssertEqual(existenceFilterMismatchInfo.localCacheCount, 35);
  1659. XCTAssertEqual(existenceFilterMismatchInfo.existenceFilterCount, 25);
  1660. // Verify that Watch sent a valid bloom filter.
  1661. FSTTestingHooksBloomFilter *bloomFilter = existenceFilterMismatchInfo.bloomFilter;
  1662. XCTAssertNotNil(bloomFilter,
  1663. "Watch should have included a bloom filter in the existence filter");
  1664. // Verify that the bloom filter was successfully used to avert a full requery. If a false
  1665. // positive occurred then retry the entire test. Although statistically rare, false positives
  1666. // are expected to happen occasionally. When a false positive _does_ happen, just retry the test
  1667. // with a different set of documents. If that retry _also_ experiences a false positive, then
  1668. // fail the test because that is so improbable that something must have gone wrong.
  1669. if (attemptNumber == 1 && !bloomFilter.applied) {
  1670. continue;
  1671. }
  1672. XCTAssertTrue(bloomFilter.applied,
  1673. @"The bloom filter should have been successfully applied with attemptNumber=%@",
  1674. @(attemptNumber));
  1675. // Break out of the test loop now that the test passes.
  1676. break;
  1677. }
  1678. }
  1679. - (void)testBloomFilterShouldCorrectlyEncodeComplexUnicodeCharacters {
  1680. // TODO(b/291365820): Stop skipping this test when running against the Firestore emulator once
  1681. // the emulator is improved to include a bloom filter in the existence filter messages that it
  1682. // sends.
  1683. XCTSkipIf([FSTIntegrationTestCase isRunningAgainstEmulator],
  1684. "Skip this test when running against the Firestore emulator because the emulator does "
  1685. "not include a bloom filter when it sends existence filter messages, making it "
  1686. "impossible for this test to verify the correctness of the bloom filter.");
  1687. // Set this test to stop when the first failure occurs because some test assertion failures make
  1688. // the rest of the test not applicable or will even crash.
  1689. [self setContinueAfterFailure:NO];
  1690. // Define a comparator that compares `NSString` objects in a way that orders canonically-
  1691. // equivalent, but distinct, strings in a consistent manner by using `NSForcedOrderingSearch`.
  1692. // Otherwise, the bare `[NSString compare:]` method considers canonically-equivalent, but
  1693. // distinct, strings as "equal" and orders them indeterminately.
  1694. NSComparator sortComparator = ^(NSString *string1, NSString *string2) {
  1695. return [string1 compare:string2 options:NSForcedOrderingSearch];
  1696. };
  1697. // Firestore does not do any Unicode normalization on the document IDs. Therefore, two document
  1698. // IDs that are canonically-equivalent (i.e. they visually appear identical) but are represented
  1699. // by a different sequence of Unicode code points are treated as distinct document IDs.
  1700. NSArray<NSString *> *testDocIds;
  1701. {
  1702. NSMutableArray<NSString *> *testDocIdsAccumulator = [[NSMutableArray alloc] init];
  1703. [testDocIdsAccumulator addObject:@"DocumentToDelete"];
  1704. // The next two strings both end with "e" with an accent: the first uses the dedicated Unicode
  1705. // code point for this character, while the second uses the standard lowercase "e" followed by
  1706. // the accent combining character.
  1707. [testDocIdsAccumulator addObject:@"LowercaseEWithAcuteAccent_\u00E9"];
  1708. [testDocIdsAccumulator addObject:@"LowercaseEWithAcuteAccent_\u0065\u0301"];
  1709. // The next two strings both end with an "e" with two different accents applied via the
  1710. // following two combining characters. The combining characters are specified in a different
  1711. // order and Firestore treats these document IDs as unique, despite the order of the combining
  1712. // characters being irrelevant.
  1713. [testDocIdsAccumulator addObject:@"LowercaseEWithMultipleAccents_\u0065\u0301\u0327"];
  1714. [testDocIdsAccumulator addObject:@"LowercaseEWithMultipleAccents_\u0065\u0327\u0301"];
  1715. // The next string contains a character outside the BMP (the "basic multilingual plane"); that
  1716. // is, its code point is greater than 0xFFFF. Since NSString stores text in sequences of 16-bit
  1717. // code units, using the UTF-16 encoding (according to
  1718. // https://www.objc.io/issues/9-strings/unicode) it is stored as a surrogate pair, two 16-bit
  1719. // code units U+D83D and U+DE00, to represent this character. Make sure that its presence is
  1720. // correctly tested in the bloom filter, which uses UTF-8 encoding.
  1721. [testDocIdsAccumulator addObject:@"Smiley_\U0001F600"];
  1722. testDocIds = [NSArray arrayWithArray:testDocIdsAccumulator];
  1723. }
  1724. // Verify assumptions about the equivalence of strings in `testDocIds`.
  1725. XCTAssertEqualObjects(testDocIds[1].decomposedStringWithCanonicalMapping,
  1726. testDocIds[2].decomposedStringWithCanonicalMapping);
  1727. XCTAssertEqualObjects(testDocIds[3].decomposedStringWithCanonicalMapping,
  1728. testDocIds[4].decomposedStringWithCanonicalMapping);
  1729. XCTAssertEqual([testDocIds[5] characterAtIndex:7], 0xD83D);
  1730. XCTAssertEqual([testDocIds[5] characterAtIndex:8], 0xDE00);
  1731. // Create the mapping from document ID to document data for the document IDs specified in
  1732. // `testDocIds`.
  1733. NSMutableDictionary<NSString *, NSDictionary<NSString *, id> *> *testDocs =
  1734. [[NSMutableDictionary alloc] init];
  1735. for (NSString *testDocId in testDocIds) {
  1736. [testDocs setValue:@{@"foo" : @42} forKey:testDocId];
  1737. }
  1738. // Create the documents whose names contain complex Unicode characters in a new collection.
  1739. FIRCollectionReference *collRef = [self collectionRefWithDocuments:testDocs];
  1740. // Run a query to populate the local cache with documents that have names with complex Unicode
  1741. // characters.
  1742. {
  1743. FIRQuerySnapshot *querySnapshot1 = [self readDocumentSetForRef:collRef
  1744. source:FIRFirestoreSourceDefault];
  1745. XCTAssertEqualObjects(
  1746. [FIRQuerySnapshotGetIDs(querySnapshot1) sortedArrayUsingComparator:sortComparator],
  1747. [testDocIds sortedArrayUsingComparator:sortComparator],
  1748. @"querySnapshot1 has the wrong documents");
  1749. }
  1750. // Delete one of the documents so that the next call to collection.get() will experience an
  1751. // existence filter mismatch. Use a different Firestore instance to avoid affecting the local
  1752. // cache.
  1753. FIRDocumentReference *documentToDelete = [collRef documentWithPath:@"DocumentToDelete"];
  1754. {
  1755. FIRFirestore *db2 = [self firestore];
  1756. [self deleteDocumentRef:[db2 documentWithPath:documentToDelete.path]];
  1757. }
  1758. // Wait for 10 seconds, during which Watch will stop tracking the query and will send an
  1759. // existence filter rather than "delete" events when the query is resumed.
  1760. [NSThread sleepForTimeInterval:10.0f];
  1761. // Resume the query and save the resulting snapshot for verification. Use some internal testing
  1762. // hooks to "capture" the existence filter mismatches.
  1763. __block FIRQuerySnapshot *querySnapshot2;
  1764. NSArray<FSTTestingHooksExistenceFilterMismatchInfo *> *existenceFilterMismatches =
  1765. [FSTTestingHooks captureExistenceFilterMismatchesDuringBlock:^{
  1766. querySnapshot2 = [self readDocumentSetForRef:collRef source:FIRFirestoreSourceDefault];
  1767. }];
  1768. // Verify that the snapshot from the resumed query contains the expected documents; that is, that
  1769. // it contains the documents whose names contain complex Unicode characters and _not_ the document
  1770. // that was deleted.
  1771. {
  1772. NSMutableArray<NSString *> *querySnapshot2ExpectedDocumentIds =
  1773. [NSMutableArray arrayWithArray:testDocIds];
  1774. [querySnapshot2ExpectedDocumentIds removeObject:documentToDelete.documentID];
  1775. XCTAssertEqualObjects(
  1776. [FIRQuerySnapshotGetIDs(querySnapshot2) sortedArrayUsingComparator:sortComparator],
  1777. [querySnapshot2ExpectedDocumentIds sortedArrayUsingComparator:sortComparator],
  1778. @"querySnapshot2 has the wrong documents");
  1779. }
  1780. // Verify that Watch sent an existence filter with the correct counts.
  1781. XCTAssertEqual(existenceFilterMismatches.count, 1u,
  1782. @"Watch should have sent exactly 1 existence filter");
  1783. FSTTestingHooksExistenceFilterMismatchInfo *existenceFilterMismatchInfo =
  1784. existenceFilterMismatches[0];
  1785. XCTAssertEqual(existenceFilterMismatchInfo.localCacheCount, (int)testDocIds.count);
  1786. XCTAssertEqual(existenceFilterMismatchInfo.existenceFilterCount, (int)testDocIds.count - 1);
  1787. // Verify that Watch sent a valid bloom filter.
  1788. FSTTestingHooksBloomFilter *bloomFilter = existenceFilterMismatchInfo.bloomFilter;
  1789. XCTAssertNotNil(bloomFilter, "Watch should have included a bloom filter in the existence filter");
  1790. // The bloom filter application should statistically be successful almost every time; the _only_
  1791. // time when it would _not_ be successful is if there is a false positive when testing for
  1792. // 'DocumentToDelete' in the bloom filter. So verify that the bloom filter application is
  1793. // successful, unless there was a false positive.
  1794. BOOL isFalsePositive = [bloomFilter mightContain:documentToDelete];
  1795. XCTAssertEqual(bloomFilter.applied, !isFalsePositive);
  1796. // Verify that the bloom filter contains the document paths with complex Unicode characters.
  1797. for (FIRDocumentSnapshot *documentSnapshot in querySnapshot2.documents) {
  1798. XCTAssertTrue([bloomFilter mightContain:documentSnapshot.reference],
  1799. @"The bloom filter should contain %@", documentSnapshot.documentID);
  1800. }
  1801. }
  1802. @end