FIRQueryTests.mm 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573
  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. - (void)testLimitQueries {
  29. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  30. @"a" : @{@"k" : @"a"},
  31. @"b" : @{@"k" : @"b"},
  32. @"c" : @{@"k" : @"c"}
  33. }];
  34. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:[collRef queryLimitedTo:2]];
  35. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ @{@"k" : @"a"}, @{@"k" : @"b"} ]));
  36. }
  37. - (void)testLimitQueriesWithDescendingSortOrder {
  38. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  39. @"a" : @{@"k" : @"a", @"sort" : @0},
  40. @"b" : @{@"k" : @"b", @"sort" : @1},
  41. @"c" : @{@"k" : @"c", @"sort" : @1},
  42. @"d" : @{@"k" : @"d", @"sort" : @2},
  43. }];
  44. FIRQuerySnapshot *snapshot =
  45. [self readDocumentSetForRef:[[collRef queryOrderedByField:@"sort"
  46. descending:YES] queryLimitedTo:2]];
  47. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  48. (@[ @{@"k" : @"d", @"sort" : @2}, @{@"k" : @"c", @"sort" : @1} ]));
  49. }
  50. - (void)testLimitToLastMustAlsoHaveExplicitOrderBy {
  51. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{}];
  52. FIRQuery *query = [collRef queryLimitedToLast:2];
  53. FSTAssertThrows([query getDocumentsWithCompletion:^(FIRQuerySnapshot *, NSError *){
  54. }],
  55. @"limit(toLast:) queries require specifying at least one OrderBy() clause.");
  56. }
  57. // Two queries that mapped to the same target ID are referred to as
  58. // "mirror queries". An example for a mirror query is a limitToLast()
  59. // query and a limit() query that share the same backend Target ID.
  60. // Since limitToLast() queries are sent to the backend with a modified
  61. // orderBy() clause, they can map to the same target representation as
  62. // limit() query, even if both queries appear separate to the user.
  63. - (void)testListenUnlistenRelistenSequenceOfMirrorQueries {
  64. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  65. @"a" : @{@"k" : @"a", @"sort" : @0},
  66. @"b" : @{@"k" : @"b", @"sort" : @1},
  67. @"c" : @{@"k" : @"c", @"sort" : @1},
  68. @"d" : @{@"k" : @"d", @"sort" : @2},
  69. }];
  70. // Setup a `limit` query.
  71. FIRQuery *limit = [[collRef queryOrderedByField:@"sort" descending:NO] queryLimitedTo:2];
  72. FSTEventAccumulator *limitAccumulator = [FSTEventAccumulator accumulatorForTest:self];
  73. id<FIRListenerRegistration> limitRegistration =
  74. [limit addSnapshotListener:limitAccumulator.valueEventHandler];
  75. // Setup a mirroring `limitToLast` query.
  76. FIRQuery *limitToLast = [[collRef queryOrderedByField:@"sort"
  77. descending:YES] queryLimitedToLast:2];
  78. FSTEventAccumulator *limitToLastAccumulator = [FSTEventAccumulator accumulatorForTest:self];
  79. id<FIRListenerRegistration> limitToLastRegistration =
  80. [limitToLast addSnapshotListener:limitToLastAccumulator.valueEventHandler];
  81. // Verify both queries get expected result.
  82. FIRQuerySnapshot *snapshot = [limitAccumulator awaitEventWithName:@"Snapshot"];
  83. NSArray *expected = @[ @{@"k" : @"a", @"sort" : @0}, @{@"k" : @"b", @"sort" : @1} ];
  84. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  85. snapshot = [limitToLastAccumulator awaitEventWithName:@"Snapshot"];
  86. expected = @[ @{@"k" : @"b", @"sort" : @1}, @{@"k" : @"a", @"sort" : @0} ];
  87. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  88. // Unlisten then re-listen limit query.
  89. [limitRegistration remove];
  90. [limit addSnapshotListener:[limitAccumulator valueEventHandler]];
  91. // Verify limit query still works.
  92. snapshot = [limitAccumulator awaitEventWithName:@"Snapshot"];
  93. expected = @[ @{@"k" : @"a", @"sort" : @0}, @{@"k" : @"b", @"sort" : @1} ];
  94. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  95. // Add a document that would change the result set.
  96. [self addDocumentRef:collRef data:@{@"k" : @"e", @"sort" : @-1}];
  97. // Verify both queries get expected result.
  98. snapshot = [limitAccumulator awaitEventWithName:@"Snapshot"];
  99. expected = @[ @{@"k" : @"e", @"sort" : @-1}, @{@"k" : @"a", @"sort" : @0} ];
  100. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  101. snapshot = [limitToLastAccumulator awaitEventWithName:@"Snapshot"];
  102. expected = @[ @{@"k" : @"a", @"sort" : @0}, @{@"k" : @"e", @"sort" : @-1} ];
  103. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  104. // Unlisten to limitToLast, update a doc, then relisten to limitToLast
  105. [limitToLastRegistration remove];
  106. [self updateDocumentRef:[collRef documentWithPath:@"a"] data:@{@"k" : @"a", @"sort" : @-2}];
  107. [limitToLast addSnapshotListener:[limitToLastAccumulator valueEventHandler]];
  108. // Verify both queries get expected result.
  109. snapshot = [limitAccumulator awaitEventWithName:@"Snapshot"];
  110. expected = @[ @{@"k" : @"a", @"sort" : @-2}, @{@"k" : @"e", @"sort" : @-1} ];
  111. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  112. snapshot = [limitToLastAccumulator awaitEventWithName:@"Snapshot"];
  113. expected = @[ @{@"k" : @"e", @"sort" : @-1}, @{@"k" : @"a", @"sort" : @-2} ];
  114. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), expected);
  115. }
  116. - (void)testLimitToLastQueriesWithCursors {
  117. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  118. @"a" : @{@"k" : @"a", @"sort" : @0},
  119. @"b" : @{@"k" : @"b", @"sort" : @1},
  120. @"c" : @{@"k" : @"c", @"sort" : @1},
  121. @"d" : @{@"k" : @"d", @"sort" : @2},
  122. }];
  123. FIRQuerySnapshot *snapshot =
  124. [self readDocumentSetForRef:[[[collRef queryOrderedByField:@"sort"] queryLimitedToLast:3]
  125. queryEndingBeforeValues:@[ @2 ]]];
  126. XCTAssertEqualObjects(
  127. FIRQuerySnapshotGetData(snapshot), (@[
  128. @{@"k" : @"a", @"sort" : @0}, @{@"k" : @"b", @"sort" : @1}, @{@"k" : @"c", @"sort" : @1}
  129. ]));
  130. snapshot = [self readDocumentSetForRef:[[[collRef queryOrderedByField:@"sort"]
  131. queryLimitedToLast:3] queryEndingAtValues:@[ @1 ]]];
  132. XCTAssertEqualObjects(
  133. FIRQuerySnapshotGetData(snapshot), (@[
  134. @{@"k" : @"a", @"sort" : @0}, @{@"k" : @"b", @"sort" : @1}, @{@"k" : @"c", @"sort" : @1}
  135. ]));
  136. snapshot = [self readDocumentSetForRef:[[[collRef queryOrderedByField:@"sort"]
  137. queryLimitedToLast:3] queryStartingAtValues:@[ @2 ]]];
  138. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ @{@"k" : @"d", @"sort" : @2} ]));
  139. snapshot =
  140. [self readDocumentSetForRef:[[[collRef queryOrderedByField:@"sort"] queryLimitedToLast:3]
  141. queryStartingAfterValues:@[ @0 ]]];
  142. XCTAssertEqualObjects(
  143. FIRQuerySnapshotGetData(snapshot), (@[
  144. @{@"k" : @"b", @"sort" : @1}, @{@"k" : @"c", @"sort" : @1}, @{@"k" : @"d", @"sort" : @2}
  145. ]));
  146. snapshot =
  147. [self readDocumentSetForRef:[[[collRef queryOrderedByField:@"sort"] queryLimitedToLast:3]
  148. queryStartingAfterValues:@[ @-1 ]]];
  149. XCTAssertEqualObjects(
  150. FIRQuerySnapshotGetData(snapshot), (@[
  151. @{@"k" : @"b", @"sort" : @1}, @{@"k" : @"c", @"sort" : @1}, @{@"k" : @"d", @"sort" : @2}
  152. ]));
  153. }
  154. - (void)testKeyOrderIsDescendingForDescendingInequality {
  155. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  156. @"a" : @{@"foo" : @42},
  157. @"b" : @{@"foo" : @42.0},
  158. @"c" : @{@"foo" : @42},
  159. @"d" : @{@"foo" : @21},
  160. @"e" : @{@"foo" : @21.0},
  161. @"f" : @{@"foo" : @66},
  162. @"g" : @{@"foo" : @66.0},
  163. }];
  164. FIRQuerySnapshot *snapshot =
  165. [self readDocumentSetForRef:[[collRef queryWhereField:@"foo"
  166. isGreaterThan:@21] queryOrderedByField:@"foo"
  167. descending:YES]];
  168. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"g", @"f", @"c", @"b", @"a" ]));
  169. }
  170. - (void)testUnaryFilterQueries {
  171. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  172. @"a" : @{@"null" : [NSNull null], @"nan" : @(NAN)},
  173. @"b" : @{@"null" : [NSNull null], @"nan" : @0},
  174. @"c" : @{@"null" : @NO, @"nan" : @(NAN)}
  175. }];
  176. FIRQuerySnapshot *results =
  177. [self readDocumentSetForRef:[[collRef queryWhereField:@"null"
  178. isEqualTo:[NSNull null]] queryWhereField:@"nan"
  179. isEqualTo:@(NAN)]];
  180. XCTAssertEqualObjects(FIRQuerySnapshotGetData(results),
  181. (@[ @{@"null" : [NSNull null], @"nan" : @(NAN)} ]));
  182. }
  183. - (void)testQueryWithFieldPaths {
  184. FIRCollectionReference *collRef = [self
  185. collectionRefWithDocuments:@{@"a" : @{@"a" : @1}, @"b" : @{@"a" : @2}, @"c" : @{@"a" : @3}}];
  186. FIRQuery *query = [collRef queryWhereFieldPath:[[FIRFieldPath alloc] initWithFields:@[ @"a" ]]
  187. isLessThan:@3];
  188. query = [query queryOrderedByFieldPath:[[FIRFieldPath alloc] initWithFields:@[ @"a" ]]
  189. descending:YES];
  190. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:query];
  191. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"b", @"a" ]));
  192. }
  193. - (void)testQueryWithPredicate {
  194. FIRCollectionReference *collRef = [self
  195. collectionRefWithDocuments:@{@"a" : @{@"a" : @1}, @"b" : @{@"a" : @2}, @"c" : @{@"a" : @3}}];
  196. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"a < 3"];
  197. FIRQuery *query = [collRef queryFilteredUsingPredicate:predicate];
  198. query = [query queryOrderedByFieldPath:[[FIRFieldPath alloc] initWithFields:@[ @"a" ]]
  199. descending:YES];
  200. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:query];
  201. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(snapshot), (@[ @"b", @"a" ]));
  202. }
  203. - (void)testFilterOnInfinity {
  204. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  205. @"a" : @{@"inf" : @(INFINITY)},
  206. @"b" : @{@"inf" : @(-INFINITY)}
  207. }];
  208. FIRQuerySnapshot *results = [self readDocumentSetForRef:[collRef queryWhereField:@"inf"
  209. isEqualTo:@(INFINITY)]];
  210. XCTAssertEqualObjects(FIRQuerySnapshotGetData(results), (@[ @{@"inf" : @(INFINITY)} ]));
  211. }
  212. - (void)testCanExplicitlySortByDocumentID {
  213. NSDictionary *testDocs = @{
  214. @"a" : @{@"key" : @"a"},
  215. @"b" : @{@"key" : @"b"},
  216. @"c" : @{@"key" : @"c"},
  217. };
  218. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  219. // Ideally this would be descending to validate it's different than
  220. // the default, but that requires an extra index
  221. FIRQuerySnapshot *docs =
  222. [self readDocumentSetForRef:[collection queryOrderedByFieldPath:[FIRFieldPath documentID]]];
  223. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs),
  224. (@[ testDocs[@"a"], testDocs[@"b"], testDocs[@"c"] ]));
  225. }
  226. - (void)testCanQueryByDocumentID {
  227. NSDictionary *testDocs = @{
  228. @"aa" : @{@"key" : @"aa"},
  229. @"ab" : @{@"key" : @"ab"},
  230. @"ba" : @{@"key" : @"ba"},
  231. @"bb" : @{@"key" : @"bb"},
  232. };
  233. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  234. FIRQuerySnapshot *docs =
  235. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  236. isEqualTo:@"ab"]];
  237. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs), (@[ testDocs[@"ab"] ]));
  238. }
  239. - (void)testCanQueryByDocumentIDs {
  240. NSDictionary *testDocs = @{
  241. @"aa" : @{@"key" : @"aa"},
  242. @"ab" : @{@"key" : @"ab"},
  243. @"ba" : @{@"key" : @"ba"},
  244. @"bb" : @{@"key" : @"bb"},
  245. };
  246. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  247. FIRQuerySnapshot *docs =
  248. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  249. isEqualTo:@"ab"]];
  250. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs), (@[ testDocs[@"ab"] ]));
  251. docs = [self readDocumentSetForRef:[[collection queryWhereFieldPath:[FIRFieldPath documentID]
  252. isGreaterThan:@"aa"]
  253. queryWhereFieldPath:[FIRFieldPath documentID]
  254. isLessThanOrEqualTo:@"ba"]];
  255. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs), (@[ testDocs[@"ab"], testDocs[@"ba"] ]));
  256. }
  257. - (void)testCanQueryByDocumentIDsUsingRefs {
  258. NSDictionary *testDocs = @{
  259. @"aa" : @{@"key" : @"aa"},
  260. @"ab" : @{@"key" : @"ab"},
  261. @"ba" : @{@"key" : @"ba"},
  262. @"bb" : @{@"key" : @"bb"},
  263. };
  264. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  265. FIRQuerySnapshot *docs = [self
  266. readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  267. isEqualTo:[collection documentWithPath:@"ab"]]];
  268. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs), (@[ testDocs[@"ab"] ]));
  269. docs = [self
  270. readDocumentSetForRef:[[collection queryWhereFieldPath:[FIRFieldPath documentID]
  271. isGreaterThan:[collection documentWithPath:@"aa"]]
  272. queryWhereFieldPath:[FIRFieldPath documentID]
  273. isLessThanOrEqualTo:[collection documentWithPath:@"ba"]]];
  274. XCTAssertEqualObjects(FIRQuerySnapshotGetData(docs), (@[ testDocs[@"ab"], testDocs[@"ba"] ]));
  275. }
  276. - (void)testWatchSurvivesNetworkDisconnect {
  277. XCTestExpectation *testExpectiation =
  278. [self expectationWithDescription:@"testWatchSurvivesNetworkDisconnect"];
  279. FIRCollectionReference *collectionRef = [self collectionRef];
  280. FIRDocumentReference *docRef = [collectionRef documentWithAutoID];
  281. FIRFirestore *firestore = collectionRef.firestore;
  282. [collectionRef
  283. addSnapshotListenerWithIncludeMetadataChanges:YES
  284. listener:^(FIRQuerySnapshot *snapshot, NSError *error) {
  285. XCTAssertNil(error);
  286. if (!snapshot.empty && !snapshot.metadata.fromCache) {
  287. [testExpectiation fulfill];
  288. }
  289. }];
  290. [firestore disableNetworkWithCompletion:^(NSError *error) {
  291. XCTAssertNil(error);
  292. [docRef setData:@{@"foo" : @"bar"}];
  293. [firestore enableNetworkWithCompletion:^(NSError *error) {
  294. XCTAssertNil(error);
  295. }];
  296. }];
  297. [self awaitExpectations];
  298. }
  299. - (void)testQueriesFireFromCacheWhenOffline {
  300. NSDictionary *testDocs = @{
  301. @"a" : @{@"foo" : @1},
  302. };
  303. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  304. id<FIRListenerRegistration> registration = [collection
  305. addSnapshotListenerWithIncludeMetadataChanges:YES
  306. listener:self.eventAccumulator.valueEventHandler];
  307. FIRQuerySnapshot *querySnap = [self.eventAccumulator awaitEventWithName:@"initial event"];
  308. XCTAssertEqualObjects(FIRQuerySnapshotGetData(querySnap), @[ @{@"foo" : @1} ]);
  309. XCTAssertEqual(querySnap.metadata.isFromCache, NO);
  310. [self disableNetwork];
  311. querySnap = [self.eventAccumulator awaitEventWithName:@"offline event with isFromCache=YES"];
  312. XCTAssertEqual(querySnap.metadata.isFromCache, YES);
  313. [self enableNetwork];
  314. querySnap = [self.eventAccumulator awaitEventWithName:@"back online event with isFromCache=NO"];
  315. XCTAssertEqual(querySnap.metadata.isFromCache, NO);
  316. [registration remove];
  317. }
  318. - (void)testQueriesCanRaiseInitialSnapshotFromCachedEmptyResults {
  319. FIRCollectionReference *collection = [self collectionRefWithDocuments:@{}];
  320. // Populate the cache with empty query result.
  321. FIRQuerySnapshot *querySnapshotA = [self readDocumentSetForRef:collection];
  322. XCTAssertFalse(querySnapshotA.metadata.fromCache);
  323. XCTAssertEqualObjects(FIRQuerySnapshotGetData(querySnapshotA), @[]);
  324. // Add a snapshot listener whose first event should be raised from cache.
  325. id<FIRListenerRegistration> registration = [collection
  326. addSnapshotListenerWithIncludeMetadataChanges:YES
  327. listener:self.eventAccumulator.valueEventHandler];
  328. FIRQuerySnapshot *querySnapshotB = [self.eventAccumulator awaitEventWithName:@"initial event"];
  329. XCTAssertTrue(querySnapshotB.metadata.fromCache);
  330. XCTAssertEqualObjects(FIRQuerySnapshotGetData(querySnapshotB), @[]);
  331. [registration remove];
  332. }
  333. - (void)testQueriesCanRaiseInitialSnapshotFromEmptyDueToDeleteCachedResults {
  334. NSDictionary *testDocs = @{
  335. @"a" : @{@"foo" : @1},
  336. };
  337. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  338. // Populate the cache with a single document.
  339. FIRQuerySnapshot *querySnapshotA = [self readDocumentSetForRef:collection];
  340. XCTAssertFalse(querySnapshotA.metadata.fromCache);
  341. XCTAssertEqualObjects(FIRQuerySnapshotGetData(querySnapshotA), @[ @{@"foo" : @1} ]);
  342. // Delete the document, making the cached query result empty.
  343. FIRDocumentReference *docRef = [collection documentWithPath:@"a"];
  344. [self deleteDocumentRef:docRef];
  345. // Add a snapshot listener whose first event should be raised from cache.
  346. id<FIRListenerRegistration> registration = [collection
  347. addSnapshotListenerWithIncludeMetadataChanges:YES
  348. listener:self.eventAccumulator.valueEventHandler];
  349. FIRQuerySnapshot *querySnapshotB = [self.eventAccumulator awaitEventWithName:@"initial event"];
  350. XCTAssertTrue(querySnapshotB.metadata.fromCache);
  351. XCTAssertEqualObjects(FIRQuerySnapshotGetData(querySnapshotB), @[]);
  352. [registration remove];
  353. }
  354. - (void)testDocumentChangesUseNSNotFound {
  355. NSDictionary *testDocs = @{
  356. @"a" : @{@"foo" : @1},
  357. };
  358. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  359. id<FIRListenerRegistration> registration =
  360. [collection addSnapshotListener:self.eventAccumulator.valueEventHandler];
  361. FIRQuerySnapshot *querySnap = [self.eventAccumulator awaitEventWithName:@"initial event"];
  362. XCTAssertEqual(querySnap.documentChanges.count, 1ul);
  363. FIRDocumentChange *change = querySnap.documentChanges[0];
  364. XCTAssertEqual(change.oldIndex, NSNotFound);
  365. XCTAssertEqual(change.newIndex, 0ul);
  366. FIRDocumentReference *doc = change.document.reference;
  367. [self deleteDocumentRef:doc];
  368. querySnap = [self.eventAccumulator awaitEventWithName:@"delete"];
  369. XCTAssertEqual(querySnap.documentChanges.count, 1ul);
  370. change = querySnap.documentChanges[0];
  371. XCTAssertEqual(change.oldIndex, 0ul);
  372. XCTAssertEqual(change.newIndex, NSNotFound);
  373. [registration remove];
  374. }
  375. - (void)testCanHaveMultipleMutationsWhileOffline {
  376. FIRCollectionReference *col = [self collectionRef];
  377. // set a few docs to known values
  378. NSDictionary *initialDocs = @{@"doc1" : @{@"key1" : @"value1"}, @"doc2" : @{@"key2" : @"value2"}};
  379. [self writeAllDocuments:initialDocs toCollection:col];
  380. // go offline for the rest of this test
  381. [self disableNetwork];
  382. // apply *multiple* mutations while offline
  383. [[col documentWithPath:@"doc1"] setData:@{@"key1b" : @"value1b"}];
  384. [[col documentWithPath:@"doc2"] setData:@{@"key2b" : @"value2b"}];
  385. FIRQuerySnapshot *result = [self readDocumentSetForRef:col];
  386. XCTAssertEqualObjects(FIRQuerySnapshotGetData(result), (@[
  387. @{@"key1b" : @"value1b"},
  388. @{@"key2b" : @"value2b"},
  389. ]));
  390. }
  391. - (void)testQueriesCanUseNotEqualFilters {
  392. // These documents are ordered by value in "zip" since notEquals filter is an inequality, which
  393. // results in documents being sorted by value.
  394. NSDictionary *testDocs = @{
  395. @"a" : @{@"zip" : @(NAN)},
  396. @"b" : @{@"zip" : @91102},
  397. @"c" : @{@"zip" : @98101},
  398. @"d" : @{@"zip" : @98103},
  399. @"e" : @{@"zip" : @[ @98101 ]},
  400. @"f" : @{@"zip" : @[ @98101, @98102 ]},
  401. @"g" : @{@"zip" : @[ @"98101", @{@"zip" : @98101} ]},
  402. @"h" : @{@"zip" : @{@"code" : @500}},
  403. @"i" : @{@"zip" : [NSNull null]},
  404. @"j" : @{@"code" : @500},
  405. };
  406. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  407. // Search for zips not matching 98101.
  408. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  409. isNotEqualTo:@98101]];
  410. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  411. testDocs[@"a"], testDocs[@"b"], testDocs[@"d"], testDocs[@"e"],
  412. testDocs[@"f"], testDocs[@"g"], testDocs[@"h"]
  413. ]));
  414. // With objects.
  415. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  416. isNotEqualTo:@{@"code" : @500}]];
  417. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  418. testDocs[@"a"], testDocs[@"b"], testDocs[@"c"], testDocs[@"d"],
  419. testDocs[@"e"], testDocs[@"f"], testDocs[@"g"]
  420. ]));
  421. // With null.
  422. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  423. isNotEqualTo:@[ [NSNull null] ]]];
  424. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  425. testDocs[@"a"], testDocs[@"b"], testDocs[@"c"], testDocs[@"d"],
  426. testDocs[@"e"], testDocs[@"f"], testDocs[@"g"], testDocs[@"h"]
  427. ]));
  428. // With NAN.
  429. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip" isNotEqualTo:@(NAN)]];
  430. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  431. testDocs[@"b"], testDocs[@"c"], testDocs[@"d"], testDocs[@"e"],
  432. testDocs[@"f"], testDocs[@"g"], testDocs[@"h"]
  433. ]));
  434. }
  435. - (void)testQueriesCanUseNotEqualFiltersWithDocIds {
  436. NSDictionary *testDocs = @{
  437. @"aa" : @{@"key" : @"aa"},
  438. @"ab" : @{@"key" : @"ab"},
  439. @"ba" : @{@"key" : @"ba"},
  440. @"bb" : @{@"key" : @"bb"},
  441. };
  442. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  443. FIRQuerySnapshot *snapshot =
  444. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  445. isNotEqualTo:@"aa"]];
  446. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  447. (@[ testDocs[@"ab"], testDocs[@"ba"], testDocs[@"bb"] ]));
  448. }
  449. - (void)testQueriesCanUseArrayContainsFilters {
  450. NSDictionary *testDocs = @{
  451. @"a" : @{@"array" : @[ @42 ]},
  452. @"b" : @{@"array" : @[ @"a", @42, @"c" ]},
  453. @"c" : @{@"array" : @[ @41.999, @"42", @{@"a" : @[ @42 ]} ]},
  454. @"d" : @{@"array" : @[ @42 ], @"array2" : @[ @"bingo" ]},
  455. @"e" : @{@"array" : @[ [NSNull null] ]},
  456. @"f" : @{@"array" : @[ @(NAN) ]},
  457. };
  458. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  459. // Search for 42
  460. FIRQuerySnapshot *snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  461. arrayContains:@42]];
  462. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  463. (@[ testDocs[@"a"], testDocs[@"b"], testDocs[@"d"] ]));
  464. // With null.
  465. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  466. arrayContains:[NSNull null]]];
  467. XCTAssertTrue(snapshot.isEmpty);
  468. // With NAN.
  469. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  470. arrayContains:@(NAN)]];
  471. XCTAssertTrue(snapshot.isEmpty);
  472. }
  473. - (void)testQueriesCanUseInFilters {
  474. NSDictionary *testDocs = @{
  475. @"a" : @{@"zip" : @98101},
  476. @"b" : @{@"zip" : @91102},
  477. @"c" : @{@"zip" : @98103},
  478. @"d" : @{@"zip" : @[ @98101 ]},
  479. @"e" : @{@"zip" : @[ @"98101", @{@"zip" : @98101} ]},
  480. @"f" : @{@"zip" : @{@"code" : @500}},
  481. @"g" : @{@"zip" : @[ @98101, @98102 ]},
  482. @"h" : @{@"zip" : [NSNull null]},
  483. @"i" : @{@"zip" : @(NAN)}
  484. };
  485. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  486. // Search for zips matching 98101, 98103, and [98101, 98102].
  487. FIRQuerySnapshot *snapshot = [self
  488. readDocumentSetForRef:[collection queryWhereField:@"zip"
  489. in:@[ @98101, @98103, @[ @98101, @98102 ] ]]];
  490. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  491. (@[ testDocs[@"a"], testDocs[@"c"], testDocs[@"g"] ]));
  492. // With objects
  493. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  494. in:@[ @{@"code" : @500} ]]];
  495. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"f"] ]));
  496. // With null.
  497. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip" in:@[ [NSNull null] ]]];
  498. XCTAssertTrue(snapshot.isEmpty);
  499. // With null and a value.
  500. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  501. in:@[ [NSNull null], @98101 ]]];
  502. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"a"] ]));
  503. // With NAN.
  504. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip" in:@[ @(NAN) ]]];
  505. XCTAssertTrue(snapshot.isEmpty);
  506. // With NAN and a value.
  507. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  508. in:@[ @(NAN), @98101 ]]];
  509. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"a"] ]));
  510. }
  511. - (void)testQueriesCanUseInFiltersWithDocIds {
  512. NSDictionary *testDocs = @{
  513. @"aa" : @{@"key" : @"aa"},
  514. @"ab" : @{@"key" : @"ab"},
  515. @"ba" : @{@"key" : @"ba"},
  516. @"bb" : @{@"key" : @"bb"},
  517. };
  518. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  519. FIRQuerySnapshot *snapshot =
  520. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  521. in:@[ @"aa", @"ab" ]]];
  522. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"aa"], testDocs[@"ab"] ]));
  523. }
  524. - (void)testQueriesCanUseNotInFilters {
  525. // These documents are ordered by value in "zip" since the NOT_IN filter is an inequality, which
  526. // results in documents being sorted by value.
  527. NSDictionary *testDocs = @{
  528. @"a" : @{@"zip" : @(NAN)},
  529. @"b" : @{@"zip" : @91102},
  530. @"c" : @{@"zip" : @98101},
  531. @"d" : @{@"zip" : @98103},
  532. @"e" : @{@"zip" : @[ @98101 ]},
  533. @"f" : @{@"zip" : @[ @98101, @98102 ]},
  534. @"g" : @{@"zip" : @[ @"98101", @{@"zip" : @98101} ]},
  535. @"h" : @{@"zip" : @{@"code" : @500}},
  536. @"i" : @{@"zip" : [NSNull null]},
  537. @"j" : @{@"code" : @500},
  538. };
  539. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  540. // Search for zips not matching 98101, 98103, and [98101, 98102].
  541. FIRQuerySnapshot *snapshot = [self
  542. readDocumentSetForRef:[collection queryWhereField:@"zip"
  543. notIn:@[ @98101, @98103, @[ @98101, @98102 ] ]]];
  544. XCTAssertEqualObjects(
  545. FIRQuerySnapshotGetData(snapshot),
  546. (@[ testDocs[@"a"], testDocs[@"b"], testDocs[@"e"], testDocs[@"g"], testDocs[@"h"] ]));
  547. // With objects.
  548. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  549. notIn:@[ @{@"code" : @500} ]]];
  550. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  551. testDocs[@"a"], testDocs[@"b"], testDocs[@"c"], testDocs[@"d"],
  552. testDocs[@"e"], testDocs[@"f"], testDocs[@"g"]
  553. ]));
  554. // With null.
  555. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  556. notIn:@[ [NSNull null] ]]];
  557. XCTAssertTrue(snapshot.isEmpty);
  558. // With NAN.
  559. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip" notIn:@[ @(NAN) ]]];
  560. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  561. testDocs[@"b"], testDocs[@"c"], testDocs[@"d"], testDocs[@"e"],
  562. testDocs[@"f"], testDocs[@"g"], testDocs[@"h"]
  563. ]));
  564. // With NAN and a number.
  565. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"zip"
  566. notIn:@[ @(NAN), @98101 ]]];
  567. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  568. testDocs[@"b"], testDocs[@"d"], testDocs[@"e"], testDocs[@"f"],
  569. testDocs[@"g"], testDocs[@"h"]
  570. ]));
  571. }
  572. - (void)testQueriesCanUseNotInFiltersWithDocIds {
  573. NSDictionary *testDocs = @{
  574. @"aa" : @{@"key" : @"aa"},
  575. @"ab" : @{@"key" : @"ab"},
  576. @"ba" : @{@"key" : @"ba"},
  577. @"bb" : @{@"key" : @"bb"},
  578. };
  579. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  580. FIRQuerySnapshot *snapshot =
  581. [self readDocumentSetForRef:[collection queryWhereFieldPath:[FIRFieldPath documentID]
  582. notIn:@[ @"aa", @"ab" ]]];
  583. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"ba"], testDocs[@"bb"] ]));
  584. }
  585. - (void)testQueriesCanUseArrayContainsAnyFilters {
  586. NSDictionary *testDocs = @{
  587. @"a" : @{@"array" : @[ @42 ]},
  588. @"b" : @{@"array" : @[ @"a", @42, @"c" ]},
  589. @"c" : @{@"array" : @[ @41.999, @"42", @{@"a" : @[ @42 ]} ]},
  590. @"d" : @{@"array" : @[ @42 ], @"array2" : @[ @"bingo" ]},
  591. @"e" : @{@"array" : @[ @43 ]},
  592. @"f" : @{@"array" : @[ @{@"a" : @42} ]},
  593. @"g" : @{@"array" : @42},
  594. @"h" : @{@"array" : @[ [NSNull null] ]},
  595. @"i" : @{@"array" : @[ @(NAN) ]},
  596. };
  597. FIRCollectionReference *collection = [self collectionRefWithDocuments:testDocs];
  598. // Search for zips matching [42, 43].
  599. FIRQuerySnapshot *snapshot = [self
  600. readDocumentSetForRef:[collection queryWhereField:@"array" arrayContainsAny:@[ @42, @43 ]]];
  601. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot),
  602. (@[ testDocs[@"a"], testDocs[@"b"], testDocs[@"d"], testDocs[@"e"] ]));
  603. // With objects.
  604. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  605. arrayContainsAny:@[ @{@"a" : @42} ]]];
  606. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[
  607. testDocs[@"f"],
  608. ]));
  609. // With null.
  610. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  611. arrayContainsAny:@[ [NSNull null] ]]];
  612. XCTAssertTrue(snapshot.isEmpty);
  613. // With null and a value.
  614. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  615. arrayContainsAny:@[ [NSNull null], @43 ]]];
  616. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"e"] ]));
  617. // With NAN.
  618. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  619. arrayContainsAny:@[ @(NAN) ]]];
  620. XCTAssertTrue(snapshot.isEmpty);
  621. // With NAN and a value.
  622. snapshot = [self readDocumentSetForRef:[collection queryWhereField:@"array"
  623. arrayContainsAny:@[ @(NAN), @43 ]]];
  624. XCTAssertEqualObjects(FIRQuerySnapshotGetData(snapshot), (@[ testDocs[@"e"] ]));
  625. }
  626. - (void)testCollectionGroupQueries {
  627. // Use .document() to get a random collection group name to use but ensure it starts with 'b'
  628. // for predictable ordering.
  629. NSString *collectionGroup = [NSString
  630. stringWithFormat:@"b%@", [[self.db collectionWithPath:@"foo"] documentWithAutoID].documentID];
  631. NSArray *docPaths = @[
  632. @"abc/123/${collectionGroup}/cg-doc1", @"abc/123/${collectionGroup}/cg-doc2",
  633. @"${collectionGroup}/cg-doc3", @"${collectionGroup}/cg-doc4",
  634. @"def/456/${collectionGroup}/cg-doc5", @"${collectionGroup}/virtual-doc/nested-coll/not-cg-doc",
  635. @"x${collectionGroup}/not-cg-doc", @"${collectionGroup}x/not-cg-doc",
  636. @"abc/123/${collectionGroup}x/not-cg-doc", @"abc/123/x${collectionGroup}/not-cg-doc",
  637. @"abc/${collectionGroup}"
  638. ];
  639. FIRWriteBatch *batch = [self.db batch];
  640. for (NSString *docPath in docPaths) {
  641. NSString *path = [docPath stringByReplacingOccurrencesOfString:@"${collectionGroup}"
  642. withString:collectionGroup];
  643. [batch setData:@{@"x" : @1} forDocument:[self.db documentWithPath:path]];
  644. }
  645. [self commitWriteBatch:batch];
  646. FIRQuerySnapshot *querySnapshot =
  647. [self readDocumentSetForRef:[self.db collectionGroupWithID:collectionGroup]];
  648. NSArray<NSString *> *ids = FIRQuerySnapshotGetIDs(querySnapshot);
  649. XCTAssertEqualObjects(ids, (@[ @"cg-doc1", @"cg-doc2", @"cg-doc3", @"cg-doc4", @"cg-doc5" ]));
  650. }
  651. - (void)testCollectionGroupQueriesWithStartAtEndAtWithArbitraryDocumentIDs {
  652. // Use .document() to get a random collection group name to use but ensure it starts with 'b'
  653. // for predictable ordering.
  654. NSString *collectionGroup = [NSString
  655. stringWithFormat:@"b%@", [[self.db collectionWithPath:@"foo"] documentWithAutoID].documentID];
  656. NSArray *docPaths = @[
  657. @"a/a/${collectionGroup}/cg-doc1", @"a/b/a/b/${collectionGroup}/cg-doc2",
  658. @"a/b/${collectionGroup}/cg-doc3", @"a/b/c/d/${collectionGroup}/cg-doc4",
  659. @"a/c/${collectionGroup}/cg-doc5", @"${collectionGroup}/cg-doc6", @"a/b/nope/nope"
  660. ];
  661. FIRWriteBatch *batch = [self.db batch];
  662. for (NSString *docPath in docPaths) {
  663. NSString *path = [docPath stringByReplacingOccurrencesOfString:@"${collectionGroup}"
  664. withString:collectionGroup];
  665. [batch setData:@{@"x" : @1} forDocument:[self.db documentWithPath:path]];
  666. }
  667. [self commitWriteBatch:batch];
  668. FIRQuerySnapshot *querySnapshot = [self
  669. readDocumentSetForRef:[[[[self.db collectionGroupWithID:collectionGroup]
  670. queryOrderedByFieldPath:[FIRFieldPath documentID]]
  671. queryStartingAfterValues:@[ @"a/b" ]]
  672. queryEndingBeforeValues:@[
  673. [NSString stringWithFormat:@"a/b/%@/cg-doc3", collectionGroup]
  674. ]]];
  675. NSArray<NSString *> *ids = FIRQuerySnapshotGetIDs(querySnapshot);
  676. XCTAssertEqualObjects(ids, (@[ @"cg-doc2" ]));
  677. }
  678. - (void)testSnapshotListenerSortsQueryByDocumentIdInTheSameOrderAsServer {
  679. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  680. @"A" : @{@"a" : @1},
  681. @"a" : @{@"a" : @1},
  682. @"Aa" : @{@"a" : @1},
  683. @"7" : @{@"a" : @1},
  684. @"12" : @{@"a" : @1},
  685. @"__id7__" : @{@"a" : @1},
  686. @"__id12__" : @{@"a" : @1},
  687. @"__id-2__" : @{@"a" : @1},
  688. @"__id1_" : @{@"a" : @1},
  689. @"_id1__" : @{@"a" : @1},
  690. @"__id" : @{@"a" : @1},
  691. @"__id9223372036854775807__" : @{@"a" : @1},
  692. @"__id-9223372036854775808__" : @{@"a" : @1},
  693. }];
  694. FIRQuery *query = [collRef queryOrderedByFieldPath:[FIRFieldPath documentID]];
  695. NSArray<NSString *> *expectedDocs = @[
  696. @"__id-9223372036854775808__", @"__id-2__", @"__id7__", @"__id12__",
  697. @"__id9223372036854775807__", @"12", @"7", @"A", @"Aa", @"__id", @"__id1_", @"_id1__", @"a"
  698. ];
  699. FIRQuerySnapshot *getSnapshot = [self readDocumentSetForRef:query];
  700. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(getSnapshot), expectedDocs);
  701. id<FIRListenerRegistration> registration =
  702. [query addSnapshotListener:self.eventAccumulator.valueEventHandler];
  703. FIRQuerySnapshot *watchSnapshot = [self.eventAccumulator awaitEventWithName:@"Snapshot"];
  704. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(watchSnapshot), expectedDocs);
  705. [registration remove];
  706. }
  707. - (void)testSnapshotListenerSortsFilteredQueryByDocumentIdInTheSameOrderAsServer {
  708. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  709. @"A" : @{@"a" : @1},
  710. @"a" : @{@"a" : @1},
  711. @"Aa" : @{@"a" : @1},
  712. @"7" : @{@"a" : @1},
  713. @"12" : @{@"a" : @1},
  714. @"__id7__" : @{@"a" : @1},
  715. @"__id12__" : @{@"a" : @1},
  716. @"__id-2__" : @{@"a" : @1},
  717. @"__id1_" : @{@"a" : @1},
  718. @"_id1__" : @{@"a" : @1},
  719. @"__id" : @{@"a" : @1},
  720. @"__id9223372036854775807__" : @{@"a" : @1},
  721. @"__id-9223372036854775808__" : @{@"a" : @1},
  722. }];
  723. FIRQuery *query = [[[collRef queryWhereFieldPath:[FIRFieldPath documentID]
  724. isGreaterThan:@"__id7__"]
  725. queryWhereFieldPath:[FIRFieldPath documentID]
  726. isLessThanOrEqualTo:@"A"] queryOrderedByFieldPath:[FIRFieldPath documentID]];
  727. NSArray<NSString *> *expectedDocs =
  728. @[ @"__id12__", @"__id9223372036854775807__", @"12", @"7", @"A" ];
  729. FIRQuerySnapshot *getSnapshot = [self readDocumentSetForRef:query];
  730. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(getSnapshot), expectedDocs);
  731. id<FIRListenerRegistration> registration =
  732. [query addSnapshotListener:self.eventAccumulator.valueEventHandler];
  733. FIRQuerySnapshot *watchSnapshot = [self.eventAccumulator awaitEventWithName:@"Snapshot"];
  734. XCTAssertEqualObjects(FIRQuerySnapshotGetIDs(watchSnapshot), expectedDocs);
  735. [registration remove];
  736. }
  737. - (void)testSdkOrdersQueryByDocumentIdTheSameWayOnlineAndOffline {
  738. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  739. @"A" : @{@"a" : @1},
  740. @"a" : @{@"a" : @1},
  741. @"Aa" : @{@"a" : @1},
  742. @"7" : @{@"a" : @1},
  743. @"12" : @{@"a" : @1},
  744. @"__id7__" : @{@"a" : @1},
  745. @"__id12__" : @{@"a" : @1},
  746. @"__id-2__" : @{@"a" : @1},
  747. @"__id1_" : @{@"a" : @1},
  748. @"_id1__" : @{@"a" : @1},
  749. @"__id" : @{@"a" : @1},
  750. @"__id9223372036854775807__" : @{@"a" : @1},
  751. @"__id-9223372036854775808__" : @{@"a" : @1},
  752. }];
  753. [self checkOnlineAndOfflineQuery:[collRef queryOrderedByFieldPath:[FIRFieldPath documentID]]
  754. matchesResult:@[
  755. @"__id-9223372036854775808__", @"__id-2__", @"__id7__", @"__id12__",
  756. @"__id9223372036854775807__", @"12", @"7", @"A", @"Aa", @"__id", @"__id1_",
  757. @"_id1__", @"a"
  758. ]];
  759. }
  760. - (void)testCollectionGroupQueriesWithWhereFiltersOnArbitraryDocumentIDs {
  761. // Use .document() to get a random collection group name to use but ensure it starts with 'b'
  762. // for predictable ordering.
  763. NSString *collectionGroup = [NSString
  764. stringWithFormat:@"b%@", [[self.db collectionWithPath:@"foo"] documentWithAutoID].documentID];
  765. NSArray *docPaths = @[
  766. @"a/a/${collectionGroup}/cg-doc1", @"a/b/a/b/${collectionGroup}/cg-doc2",
  767. @"a/b/${collectionGroup}/cg-doc3", @"a/b/c/d/${collectionGroup}/cg-doc4",
  768. @"a/c/${collectionGroup}/cg-doc5", @"${collectionGroup}/cg-doc6", @"a/b/nope/nope"
  769. ];
  770. FIRWriteBatch *batch = [self.db batch];
  771. for (NSString *docPath in docPaths) {
  772. NSString *path = [docPath stringByReplacingOccurrencesOfString:@"${collectionGroup}"
  773. withString:collectionGroup];
  774. [batch setData:@{@"x" : @1} forDocument:[self.db documentWithPath:path]];
  775. }
  776. [self commitWriteBatch:batch];
  777. FIRQuerySnapshot *querySnapshot = [self
  778. readDocumentSetForRef:[[[self.db collectionGroupWithID:collectionGroup]
  779. queryWhereFieldPath:[FIRFieldPath documentID]
  780. isGreaterThanOrEqualTo:@"a/b"]
  781. queryWhereFieldPath:[FIRFieldPath documentID]
  782. isLessThan:[NSString stringWithFormat:@"a/b/%@/cg-doc3",
  783. collectionGroup]]];
  784. NSArray<NSString *> *ids = FIRQuerySnapshotGetIDs(querySnapshot);
  785. XCTAssertEqualObjects(ids, (@[ @"cg-doc2" ]));
  786. }
  787. - (void)testOrQueries {
  788. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  789. @"doc1" : @{@"a" : @1, @"b" : @0},
  790. @"doc2" : @{@"a" : @2, @"b" : @1},
  791. @"doc3" : @{@"a" : @3, @"b" : @2},
  792. @"doc4" : @{@"a" : @1, @"b" : @3},
  793. @"doc5" : @{@"a" : @1, @"b" : @1}
  794. }];
  795. // Two equalities: a==1 || b==1.
  796. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  797. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter filterWhereField:@"b" isEqualTo:@1]
  798. ]];
  799. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  800. matchesResult:@[ @"doc1", @"doc2", @"doc4", @"doc5" ]];
  801. // (a==1 && b==0) || (a==3 && b==2)
  802. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  803. [FIRFilter andFilterWithFilters:@[
  804. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter filterWhereField:@"b" isEqualTo:@0]
  805. ]],
  806. [FIRFilter andFilterWithFilters:@[
  807. [FIRFilter filterWhereField:@"a" isEqualTo:@3], [FIRFilter filterWhereField:@"b" isEqualTo:@2]
  808. ]]
  809. ]];
  810. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  811. matchesResult:@[ @"doc1", @"doc3" ]];
  812. // a==1 && (b==0 || b==3).
  813. FIRFilter *filter3 = [FIRFilter andFilterWithFilters:@[
  814. [FIRFilter filterWhereField:@"a" isEqualTo:@1], [FIRFilter orFilterWithFilters:@[
  815. [FIRFilter filterWhereField:@"b" isEqualTo:@0], [FIRFilter filterWhereField:@"b" isEqualTo:@3]
  816. ]]
  817. ]];
  818. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter3]
  819. matchesResult:@[ @"doc1", @"doc4" ]];
  820. // (a==2 || b==2) && (a==3 || b==3)
  821. FIRFilter *filter4 = [FIRFilter andFilterWithFilters:@[
  822. [FIRFilter orFilterWithFilters:@[
  823. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" isEqualTo:@2]
  824. ]],
  825. [FIRFilter orFilterWithFilters:@[
  826. [FIRFilter filterWhereField:@"a" isEqualTo:@3], [FIRFilter filterWhereField:@"b" isEqualTo:@3]
  827. ]]
  828. ]];
  829. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter4] matchesResult:@[ @"doc3" ]];
  830. // Test with limits without orderBy (the __name__ ordering is the tie breaker).
  831. FIRFilter *filter5 = [FIRFilter orFilterWithFilters:@[
  832. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" isEqualTo:@1]
  833. ]];
  834. [self checkOnlineAndOfflineQuery:[[collRef queryWhereFilter:filter5] queryLimitedTo:1]
  835. matchesResult:@[ @"doc2" ]];
  836. }
  837. - (void)testOrQueriesWithIn {
  838. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  839. @"doc1" : @{@"a" : @1, @"b" : @0},
  840. @"doc2" : @{@"b" : @1},
  841. @"doc3" : @{@"a" : @3, @"b" : @2},
  842. @"doc4" : @{@"a" : @1, @"b" : @3},
  843. @"doc5" : @{@"a" : @1},
  844. @"doc6" : @{@"a" : @2}
  845. }];
  846. // a==2 || b in [2,3]
  847. FIRFilter *filter = [FIRFilter orFilterWithFilters:@[
  848. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b" in:@[ @2, @3 ]]
  849. ]];
  850. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter]
  851. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  852. }
  853. - (void)testOrQueriesWithArrayMembership {
  854. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  855. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  856. @"doc2" : @{@"b" : @[ @1 ]},
  857. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ]},
  858. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  859. @"doc5" : @{@"a" : @1},
  860. @"doc6" : @{@"a" : @2}
  861. }];
  862. // a==2 || b array-contains 7
  863. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  864. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b"
  865. arrayContains:@7]
  866. ]];
  867. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  868. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  869. // a==2 || b array-contains-any [0, 3]
  870. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  871. [FIRFilter filterWhereField:@"a" isEqualTo:@2], [FIRFilter filterWhereField:@"b"
  872. arrayContainsAny:@[ @0, @3 ]]
  873. ]];
  874. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  875. matchesResult:@[ @"doc1", @"doc4", @"doc6" ]];
  876. }
  877. - (void)testMultipleInOps {
  878. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  879. @"doc1" : @{@"a" : @1, @"b" : @0},
  880. @"doc2" : @{@"b" : @1},
  881. @"doc3" : @{@"a" : @3, @"b" : @2},
  882. @"doc4" : @{@"a" : @1, @"b" : @3},
  883. @"doc5" : @{@"a" : @1},
  884. @"doc6" : @{@"a" : @2}
  885. }];
  886. // Two IN operations on different fields with disjunction.
  887. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  888. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  889. in:@[ @0, @2 ]]
  890. ]];
  891. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  892. matchesResult:@[ @"doc1", @"doc3", @"doc6" ]];
  893. // Two IN operations on the same field with disjunction.
  894. // a IN [0,3] || a IN [0,2] should union them (similar to: a IN [0,2,3]).
  895. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  896. [FIRFilter filterWhereField:@"a" in:@[ @0, @3 ]], [FIRFilter filterWhereField:@"a"
  897. in:@[ @0, @2 ]]
  898. ]];
  899. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  900. matchesResult:@[ @"doc3", @"doc6" ]];
  901. }
  902. - (void)testUsingInWithArrayContainsAny {
  903. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  904. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  905. @"doc2" : @{@"b" : @[ @1 ]},
  906. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ], @"c" : @10},
  907. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  908. @"doc5" : @{@"a" : @1},
  909. @"doc6" : @{@"a" : @2, @"c" : @20}
  910. }];
  911. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  912. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  913. arrayContainsAny:@[ @0, @7 ]]
  914. ]];
  915. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  916. matchesResult:@[ @"doc1", @"doc3", @"doc4", @"doc6" ]];
  917. FIRFilter *filter2 = [FIRFilter orFilterWithFilters:@[
  918. [FIRFilter andFilterWithFilters:@[
  919. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"c"
  920. isEqualTo:@10]
  921. ]],
  922. [FIRFilter filterWhereField:@"b" arrayContainsAny:@[ @0, @7 ]]
  923. ]];
  924. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2]
  925. matchesResult:@[ @"doc1", @"doc3", @"doc4" ]];
  926. }
  927. - (void)testUseInWithArrayContains {
  928. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  929. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  930. @"doc2" : @{@"b" : @[ @1 ]},
  931. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ]},
  932. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  933. @"doc5" : @{@"a" : @1},
  934. @"doc6" : @{@"a" : @2}
  935. }];
  936. FIRFilter *filter1 = [FIRFilter orFilterWithFilters:@[
  937. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  938. arrayContainsAny:@[ @3 ]]
  939. ]];
  940. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter1]
  941. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  942. FIRFilter *filter2 = [FIRFilter andFilterWithFilters:@[
  943. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter filterWhereField:@"b"
  944. arrayContains:@7]
  945. ]];
  946. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter2] matchesResult:@[ @"doc3" ]];
  947. FIRFilter *filter3 = [FIRFilter orFilterWithFilters:@[
  948. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter andFilterWithFilters:@[
  949. [FIRFilter filterWhereField:@"b" arrayContains:@3], [FIRFilter filterWhereField:@"a"
  950. isEqualTo:@1]
  951. ]]
  952. ]];
  953. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter3]
  954. matchesResult:@[ @"doc3", @"doc4", @"doc6" ]];
  955. FIRFilter *filter4 = [FIRFilter andFilterWithFilters:@[
  956. [FIRFilter filterWhereField:@"a" in:@[ @2, @3 ]], [FIRFilter orFilterWithFilters:@[
  957. [FIRFilter filterWhereField:@"b" arrayContains:@7], [FIRFilter filterWhereField:@"a"
  958. isEqualTo:@1]
  959. ]]
  960. ]];
  961. [self checkOnlineAndOfflineQuery:[collRef queryWhereFilter:filter4] matchesResult:@[ @"doc3" ]];
  962. }
  963. - (void)testOrderByEquality {
  964. // TODO(orquery): Enable this test against production when possible.
  965. XCTSkipIf(![FSTIntegrationTestCase isRunningAgainstEmulator],
  966. "Skip this test if running against production because order-by-equality is not "
  967. "supported yet.");
  968. FIRCollectionReference *collRef = [self collectionRefWithDocuments:@{
  969. @"doc1" : @{@"a" : @1, @"b" : @[ @0 ]},
  970. @"doc2" : @{@"b" : @[ @1 ]},
  971. @"doc3" : @{@"a" : @3, @"b" : @[ @2, @7 ], @"c" : @10},
  972. @"doc4" : @{@"a" : @1, @"b" : @[ @3, @7 ]},
  973. @"doc5" : @{@"a" : @1},
  974. @"doc6" : @{@"a" : @2, @"c" : @20}
  975. }];
  976. [self checkOnlineAndOfflineQuery:[[collRef queryWhereFilter:[FIRFilter filterWhereField:@"a"
  977. isEqualTo:@1]]
  978. queryOrderedByField:@"a"]
  979. matchesResult:@[ @"doc1", @"doc4", @"doc5" ]];
  980. [self checkOnlineAndOfflineQuery:[[collRef
  981. queryWhereFilter:[FIRFilter filterWhereField:@"a"
  982. in:@[ @2, @3 ]]]
  983. queryOrderedByField:@"a"]
  984. matchesResult:@[ @"doc6", @"doc3" ]];
  985. }
  986. - (void)testResumingAQueryShouldUseBloomFilterToAvoidFullRequery {
  987. // TODO(b/291365820): Stop skipping this test when running against the Firestore emulator once
  988. // the emulator is improved to include a bloom filter in the existence filter messages that it
  989. // sends.
  990. XCTSkipIf([FSTIntegrationTestCase isRunningAgainstEmulator],
  991. "Skip this test when running against the Firestore emulator because the emulator does "
  992. "not include a bloom filter when it sends existence filter messages, making it "
  993. "impossible for this test to verify the correctness of the bloom filter.");
  994. // Set this test to stop when the first failure occurs because some test assertion failures make
  995. // the rest of the test not applicable or will even crash.
  996. [self setContinueAfterFailure:NO];
  997. // Prepare the names and contents of the 100 documents to create.
  998. NSMutableDictionary<NSString *, NSDictionary<NSString *, id> *> *testDocs =
  999. [[NSMutableDictionary alloc] init];
  1000. for (int i = 0; i < 100; i++) {
  1001. [testDocs setValue:@{@"key" : @42} forKey:[NSString stringWithFormat:@"doc%@", @(1000 + i)]];
  1002. }
  1003. // Each iteration of the "while" loop below runs a single iteration of the test. The test will
  1004. // be run multiple times only if a bloom filter false positive occurs.
  1005. int attemptNumber = 0;
  1006. while (true) {
  1007. attemptNumber++;
  1008. // Create 100 documents in a new collection.
  1009. FIRCollectionReference *collRef = [self collectionRefWithDocuments:testDocs];
  1010. // Run a query to populate the local cache with the 100 documents and a resume token.
  1011. FIRQuerySnapshot *querySnapshot1 = [self readDocumentSetForRef:collRef
  1012. source:FIRFirestoreSourceDefault];
  1013. XCTAssertEqual(querySnapshot1.count, 100, @"querySnapshot1.count has an unexpected value");
  1014. NSArray<FIRDocumentReference *> *createdDocuments =
  1015. FIRDocumentReferenceArrayFromQuerySnapshot(querySnapshot1);
  1016. // Delete 50 of the 100 documents. Use a different Firestore instance to avoid affecting the
  1017. // local cache.
  1018. NSSet<NSString *> *deletedDocumentIds;
  1019. {
  1020. FIRFirestore *db2 = [self firestore];
  1021. FIRWriteBatch *batch = [db2 batch];
  1022. NSMutableArray<NSString *> *deletedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1023. for (decltype(createdDocuments.count) i = 0; i < createdDocuments.count; i += 2) {
  1024. FIRDocumentReference *documentToDelete = [db2 documentWithPath:createdDocuments[i].path];
  1025. [batch deleteDocument:documentToDelete];
  1026. [deletedDocumentIdsAccumulator addObject:documentToDelete.documentID];
  1027. }
  1028. [self commitWriteBatch:batch];
  1029. deletedDocumentIds = [NSSet setWithArray:deletedDocumentIdsAccumulator];
  1030. }
  1031. XCTAssertEqual(deletedDocumentIds.count, 50u, @"deletedDocumentIds has the wrong size");
  1032. // Wait for 10 seconds, during which Watch will stop tracking the query and will send an
  1033. // existence filter rather than "delete" events when the query is resumed.
  1034. [NSThread sleepForTimeInterval:10.0f];
  1035. // Resume the query and save the resulting snapshot for verification.
  1036. // Use some internal testing hooks to "capture" the existence filter mismatches to verify that
  1037. // Watch sent a bloom filter, and it was used to avert a full requery.
  1038. __block FIRQuerySnapshot *querySnapshot2;
  1039. NSArray<FSTTestingHooksExistenceFilterMismatchInfo *> *existenceFilterMismatches =
  1040. [FSTTestingHooks captureExistenceFilterMismatchesDuringBlock:^{
  1041. querySnapshot2 = [self readDocumentSetForRef:collRef source:FIRFirestoreSourceDefault];
  1042. }];
  1043. // Verify that the snapshot from the resumed query contains the expected documents; that is,
  1044. // that it contains the 50 documents that were _not_ deleted.
  1045. {
  1046. NSMutableArray<NSString *> *expectedDocumentIds = [[NSMutableArray alloc] init];
  1047. for (FIRDocumentReference *documentRef in createdDocuments) {
  1048. if (![deletedDocumentIds containsObject:documentRef.documentID]) {
  1049. [expectedDocumentIds addObject:documentRef.documentID];
  1050. }
  1051. }
  1052. XCTAssertEqualObjects([NSSet setWithArray:FIRQuerySnapshotGetIDs(querySnapshot2)],
  1053. [NSSet setWithArray:expectedDocumentIds],
  1054. @"querySnapshot2 has the wrong documents");
  1055. }
  1056. // Verify that Watch sent an existence filter with the correct counts when the query was
  1057. // resumed.
  1058. XCTAssertEqual(existenceFilterMismatches.count, 1u,
  1059. @"Watch should have sent exactly 1 existence filter");
  1060. FSTTestingHooksExistenceFilterMismatchInfo *existenceFilterMismatchInfo =
  1061. existenceFilterMismatches[0];
  1062. XCTAssertEqual(existenceFilterMismatchInfo.localCacheCount, 100);
  1063. XCTAssertEqual(existenceFilterMismatchInfo.existenceFilterCount, 50);
  1064. // Verify that Watch sent a valid bloom filter.
  1065. FSTTestingHooksBloomFilter *bloomFilter = existenceFilterMismatchInfo.bloomFilter;
  1066. XCTAssertNotNil(bloomFilter,
  1067. "Watch should have included a bloom filter in the existence filter");
  1068. XCTAssertGreaterThan(bloomFilter.hashCount, 0);
  1069. XCTAssertGreaterThan(bloomFilter.bitmapLength, 0);
  1070. XCTAssertGreaterThan(bloomFilter.padding, 0);
  1071. XCTAssertLessThan(bloomFilter.padding, 8);
  1072. // Verify that the bloom filter was successfully used to avert a full requery. If a false
  1073. // positive occurred then retry the entire test. Although statistically rare, false positives
  1074. // are expected to happen occasionally. When a false positive _does_ happen, just retry the test
  1075. // with a different set of documents. If that retry _also_ experiences a false positive, then
  1076. // fail the test because that is so improbable that something must have gone wrong.
  1077. if (attemptNumber == 1 && !bloomFilter.applied) {
  1078. continue;
  1079. }
  1080. XCTAssertTrue(bloomFilter.applied,
  1081. @"The bloom filter should have been successfully applied with attemptNumber=%@",
  1082. @(attemptNumber));
  1083. // Break out of the test loop now that the test passes.
  1084. break;
  1085. }
  1086. }
  1087. - (void)
  1088. testBloomFilterShouldAvertAFullRequeryWhenDocumentsWereAddedDeletedRemovedUpdatedAndUnchangedSinceTheResumeToken {
  1089. // TODO(b/291365820): Stop skipping this test when running against the Firestore emulator once
  1090. // the emulator is improved to include a bloom filter in the existence filter messages that it
  1091. // sends.
  1092. XCTSkipIf([FSTIntegrationTestCase isRunningAgainstEmulator],
  1093. "Skip this test when running against the Firestore emulator because the emulator does "
  1094. "not include a bloom filter when it sends existence filter messages, making it "
  1095. "impossible for this test to verify the correctness of the bloom filter.");
  1096. // Set this test to stop when the first failure occurs because some test assertion failures make
  1097. // the rest of the test not applicable or will even crash.
  1098. [self setContinueAfterFailure:NO];
  1099. // Prepare the names and contents of the 20 documents to create.
  1100. NSMutableDictionary<NSString *, NSDictionary<NSString *, id> *> *testDocs =
  1101. [[NSMutableDictionary alloc] init];
  1102. for (int i = 0; i < 20; i++) {
  1103. [testDocs setValue:@{@"key" : @42, @"removed" : @NO}
  1104. forKey:[NSString stringWithFormat:@"doc%@", @(1000 + i)]];
  1105. }
  1106. // Each iteration of the "while" loop below runs a single iteration of the test. The test will
  1107. // be run multiple times only if a bloom filter false positive occurs.
  1108. int attemptNumber = 0;
  1109. while (true) {
  1110. attemptNumber++;
  1111. // Create 20 documents in a new collection.
  1112. FIRCollectionReference *collRef = [self collectionRefWithDocuments:testDocs];
  1113. FIRQuery *query = [collRef queryWhereField:@"removed" isEqualTo:@NO];
  1114. // Run a query to populate the local cache with the 20 documents and a resume token.
  1115. FIRQuerySnapshot *querySnapshot1 = [self readDocumentSetForRef:query
  1116. source:FIRFirestoreSourceDefault];
  1117. XCTAssertEqual(querySnapshot1.count, 20u, @"querySnapshot1.count has an unexpected value");
  1118. NSArray<FIRDocumentReference *> *createdDocuments =
  1119. FIRDocumentReferenceArrayFromQuerySnapshot(querySnapshot1);
  1120. // Out of the 20 existing documents, leave 5 docs untouched, delete 5 docs, remove 5 docs,
  1121. // update 5 docs, and add 15 new docs.
  1122. NSSet<NSString *> *deletedDocumentIds;
  1123. NSSet<NSString *> *removedDocumentIds;
  1124. NSSet<NSString *> *updatedDocumentIds;
  1125. NSMutableArray<NSString *> *addedDocumentIds = [[NSMutableArray alloc] init];
  1126. {
  1127. FIRFirestore *db2 = [self firestore];
  1128. FIRWriteBatch *batch = [db2 batch];
  1129. NSMutableArray<NSString *> *deletedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1130. for (decltype(createdDocuments.count) i = 0; i < createdDocuments.count; i += 4) {
  1131. FIRDocumentReference *documentToDelete = [db2 documentWithPath:createdDocuments[i].path];
  1132. [batch deleteDocument:documentToDelete];
  1133. [deletedDocumentIdsAccumulator addObject:documentToDelete.documentID];
  1134. }
  1135. deletedDocumentIds = [NSSet setWithArray:deletedDocumentIdsAccumulator];
  1136. XCTAssertEqual(deletedDocumentIds.count, 5u, @"deletedDocumentIds has the wrong size");
  1137. // Update 5 documents to no longer match the query.
  1138. NSMutableArray<NSString *> *removedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1139. for (decltype(createdDocuments.count) i = 1; i < createdDocuments.count; i += 4) {
  1140. FIRDocumentReference *documentToRemove = [db2 documentWithPath:createdDocuments[i].path];
  1141. [batch updateData:@{@"removed" : @YES} forDocument:documentToRemove];
  1142. [removedDocumentIdsAccumulator addObject:documentToRemove.documentID];
  1143. }
  1144. removedDocumentIds = [NSSet setWithArray:removedDocumentIdsAccumulator];
  1145. XCTAssertEqual(removedDocumentIds.count, 5u, @"removedDocumentIds has the wrong size");
  1146. // Update 5 documents, but ensure they still match the query.
  1147. NSMutableArray<NSString *> *updatedDocumentIdsAccumulator = [[NSMutableArray alloc] init];
  1148. for (decltype(createdDocuments.count) i = 2; i < createdDocuments.count; i += 4) {
  1149. FIRDocumentReference *documentToUpdate = [db2 documentWithPath:createdDocuments[i].path];
  1150. [batch updateData:@{@"key" : @43} forDocument:documentToUpdate];
  1151. [updatedDocumentIdsAccumulator addObject:documentToUpdate.documentID];
  1152. }
  1153. updatedDocumentIds = [NSSet setWithArray:updatedDocumentIdsAccumulator];
  1154. XCTAssertEqual(updatedDocumentIds.count, 5u, @"updatedDocumentIds has the wrong size");
  1155. for (int i = 0; i < 15; i += 1) {
  1156. FIRDocumentReference *documentToAdd = [db2
  1157. documentWithPath:[NSString stringWithFormat:@"%@/newDoc%@", collRef.path, @(1000 + i)]];
  1158. [batch setData:@{@"key" : @42, @"removed" : @NO} forDocument:documentToAdd];
  1159. [addedDocumentIds addObject:documentToAdd.documentID];
  1160. }
  1161. // Ensure the documentIds above are mutually exclusive.
  1162. NSMutableSet<NSString *> *mergedSet = [NSMutableSet setWithArray:addedDocumentIds];
  1163. [mergedSet unionSet:deletedDocumentIds];
  1164. [mergedSet unionSet:removedDocumentIds];
  1165. [mergedSet unionSet:updatedDocumentIds];
  1166. XCTAssertEqual(mergedSet.count, 30u, @"There are documents experienced multiple operations.");
  1167. [self commitWriteBatch:batch];
  1168. }
  1169. // Wait for 10 seconds, during which Watch will stop tracking the query and will send an
  1170. // existence filter rather than "delete" events when the query is resumed.
  1171. [NSThread sleepForTimeInterval:10.0f];
  1172. // Resume the query and save the resulting snapshot for verification. Use some internal testing
  1173. // hooks to "capture" the existence filter mismatches to verify that Watch sent a bloom
  1174. // filter, and it was used to avert a full requery.
  1175. __block FIRQuerySnapshot *querySnapshot2;
  1176. NSArray<FSTTestingHooksExistenceFilterMismatchInfo *> *existenceFilterMismatches =
  1177. [FSTTestingHooks captureExistenceFilterMismatchesDuringBlock:^{
  1178. querySnapshot2 = [self readDocumentSetForRef:query source:FIRFirestoreSourceDefault];
  1179. }];
  1180. XCTAssertEqual(querySnapshot2.count, 25u, @"querySnapshot1.count has an unexpected value");
  1181. // Verify that the snapshot from the resumed query contains the expected documents; that is, 10
  1182. // existing documents that still match the query, and 15 documents that are newly added.
  1183. {
  1184. NSMutableArray<NSString *> *expectedDocumentIds = [[NSMutableArray alloc] init];
  1185. for (FIRDocumentReference *documentRef in createdDocuments) {
  1186. if (![deletedDocumentIds containsObject:documentRef.documentID] &&
  1187. ![removedDocumentIds containsObject:documentRef.documentID]) {
  1188. [expectedDocumentIds addObject:documentRef.documentID];
  1189. }
  1190. }
  1191. [expectedDocumentIds addObjectsFromArray:addedDocumentIds];
  1192. XCTAssertEqualObjects([NSSet setWithArray:FIRQuerySnapshotGetIDs(querySnapshot2)],
  1193. [NSSet setWithArray:expectedDocumentIds],
  1194. @"querySnapshot2 has the wrong documents");
  1195. }
  1196. // Verify that Watch sent an existence filter with the correct counts when the query was
  1197. // resumed.
  1198. XCTAssertEqual(existenceFilterMismatches.count, 1u,
  1199. @"Watch should have sent exactly 1 existence filter");
  1200. FSTTestingHooksExistenceFilterMismatchInfo *existenceFilterMismatchInfo =
  1201. existenceFilterMismatches[0];
  1202. XCTAssertEqual(existenceFilterMismatchInfo.localCacheCount, 35);
  1203. XCTAssertEqual(existenceFilterMismatchInfo.existenceFilterCount, 25);
  1204. // Verify that Watch sent a valid bloom filter.
  1205. FSTTestingHooksBloomFilter *bloomFilter = existenceFilterMismatchInfo.bloomFilter;
  1206. XCTAssertNotNil(bloomFilter,
  1207. "Watch should have included a bloom filter in the existence filter");
  1208. // Verify that the bloom filter was successfully used to avert a full requery. If a false
  1209. // positive occurred then retry the entire test. Although statistically rare, false positives
  1210. // are expected to happen occasionally. When a false positive _does_ happen, just retry the test
  1211. // with a different set of documents. If that retry _also_ experiences a false positive, then
  1212. // fail the test because that is so improbable that something must have gone wrong.
  1213. if (attemptNumber == 1 && !bloomFilter.applied) {
  1214. continue;
  1215. }
  1216. XCTAssertTrue(bloomFilter.applied,
  1217. @"The bloom filter should have been successfully applied with attemptNumber=%@",
  1218. @(attemptNumber));
  1219. // Break out of the test loop now that the test passes.
  1220. break;
  1221. }
  1222. }
  1223. - (void)testBloomFilterShouldCorrectlyEncodeComplexUnicodeCharacters {
  1224. // TODO(b/291365820): Stop skipping this test when running against the Firestore emulator once
  1225. // the emulator is improved to include a bloom filter in the existence filter messages that it
  1226. // sends.
  1227. XCTSkipIf([FSTIntegrationTestCase isRunningAgainstEmulator],
  1228. "Skip this test when running against the Firestore emulator because the emulator does "
  1229. "not include a bloom filter when it sends existence filter messages, making it "
  1230. "impossible for this test to verify the correctness of the bloom filter.");
  1231. // Set this test to stop when the first failure occurs because some test assertion failures make
  1232. // the rest of the test not applicable or will even crash.
  1233. [self setContinueAfterFailure:NO];
  1234. // Define a comparator that compares `NSString` objects in a way that orders canonically-
  1235. // equivalent, but distinct, strings in a consistent manner by using `NSForcedOrderingSearch`.
  1236. // Otherwise, the bare `[NSString compare:]` method considers canonically-equivalent, but
  1237. // distinct, strings as "equal" and orders them indeterminately.
  1238. NSComparator sortComparator = ^(NSString *string1, NSString *string2) {
  1239. return [string1 compare:string2 options:NSForcedOrderingSearch];
  1240. };
  1241. // Firestore does not do any Unicode normalization on the document IDs. Therefore, two document
  1242. // IDs that are canonically-equivalent (i.e. they visually appear identical) but are represented
  1243. // by a different sequence of Unicode code points are treated as distinct document IDs.
  1244. NSArray<NSString *> *testDocIds;
  1245. {
  1246. NSMutableArray<NSString *> *testDocIdsAccumulator = [[NSMutableArray alloc] init];
  1247. [testDocIdsAccumulator addObject:@"DocumentToDelete"];
  1248. // The next two strings both end with "e" with an accent: the first uses the dedicated Unicode
  1249. // code point for this character, while the second uses the standard lowercase "e" followed by
  1250. // the accent combining character.
  1251. [testDocIdsAccumulator addObject:@"LowercaseEWithAcuteAccent_\u00E9"];
  1252. [testDocIdsAccumulator addObject:@"LowercaseEWithAcuteAccent_\u0065\u0301"];
  1253. // The next two strings both end with an "e" with two different accents applied via the
  1254. // following two combining characters. The combining characters are specified in a different
  1255. // order and Firestore treats these document IDs as unique, despite the order of the combining
  1256. // characters being irrelevant.
  1257. [testDocIdsAccumulator addObject:@"LowercaseEWithMultipleAccents_\u0065\u0301\u0327"];
  1258. [testDocIdsAccumulator addObject:@"LowercaseEWithMultipleAccents_\u0065\u0327\u0301"];
  1259. // The next string contains a character outside the BMP (the "basic multilingual plane"); that
  1260. // is, its code point is greater than 0xFFFF. Since NSString stores text in sequences of 16-bit
  1261. // code units, using the UTF-16 encoding (according to
  1262. // https://www.objc.io/issues/9-strings/unicode) it is stored as a surrogate pair, two 16-bit
  1263. // code units U+D83D and U+DE00, to represent this character. Make sure that its presence is
  1264. // correctly tested in the bloom filter, which uses UTF-8 encoding.
  1265. [testDocIdsAccumulator addObject:@"Smiley_\U0001F600"];
  1266. testDocIds = [NSArray arrayWithArray:testDocIdsAccumulator];
  1267. }
  1268. // Verify assumptions about the equivalence of strings in `testDocIds`.
  1269. XCTAssertEqualObjects(testDocIds[1].decomposedStringWithCanonicalMapping,
  1270. testDocIds[2].decomposedStringWithCanonicalMapping);
  1271. XCTAssertEqualObjects(testDocIds[3].decomposedStringWithCanonicalMapping,
  1272. testDocIds[4].decomposedStringWithCanonicalMapping);
  1273. XCTAssertEqual([testDocIds[5] characterAtIndex:7], 0xD83D);
  1274. XCTAssertEqual([testDocIds[5] characterAtIndex:8], 0xDE00);
  1275. // Create the mapping from document ID to document data for the document IDs specified in
  1276. // `testDocIds`.
  1277. NSMutableDictionary<NSString *, NSDictionary<NSString *, id> *> *testDocs =
  1278. [[NSMutableDictionary alloc] init];
  1279. for (NSString *testDocId in testDocIds) {
  1280. [testDocs setValue:@{@"foo" : @42} forKey:testDocId];
  1281. }
  1282. // Create the documents whose names contain complex Unicode characters in a new collection.
  1283. FIRCollectionReference *collRef = [self collectionRefWithDocuments:testDocs];
  1284. // Run a query to populate the local cache with documents that have names with complex Unicode
  1285. // characters.
  1286. {
  1287. FIRQuerySnapshot *querySnapshot1 = [self readDocumentSetForRef:collRef
  1288. source:FIRFirestoreSourceDefault];
  1289. XCTAssertEqualObjects(
  1290. [FIRQuerySnapshotGetIDs(querySnapshot1) sortedArrayUsingComparator:sortComparator],
  1291. [testDocIds sortedArrayUsingComparator:sortComparator],
  1292. @"querySnapshot1 has the wrong documents");
  1293. }
  1294. // Delete one of the documents so that the next call to collection.get() will experience an
  1295. // existence filter mismatch. Use a different Firestore instance to avoid affecting the local
  1296. // cache.
  1297. FIRDocumentReference *documentToDelete = [collRef documentWithPath:@"DocumentToDelete"];
  1298. {
  1299. FIRFirestore *db2 = [self firestore];
  1300. [self deleteDocumentRef:[db2 documentWithPath:documentToDelete.path]];
  1301. }
  1302. // Wait for 10 seconds, during which Watch will stop tracking the query and will send an
  1303. // existence filter rather than "delete" events when the query is resumed.
  1304. [NSThread sleepForTimeInterval:10.0f];
  1305. // Resume the query and save the resulting snapshot for verification. Use some internal testing
  1306. // hooks to "capture" the existence filter mismatches.
  1307. __block FIRQuerySnapshot *querySnapshot2;
  1308. NSArray<FSTTestingHooksExistenceFilterMismatchInfo *> *existenceFilterMismatches =
  1309. [FSTTestingHooks captureExistenceFilterMismatchesDuringBlock:^{
  1310. querySnapshot2 = [self readDocumentSetForRef:collRef source:FIRFirestoreSourceDefault];
  1311. }];
  1312. // Verify that the snapshot from the resumed query contains the expected documents; that is, that
  1313. // it contains the documents whose names contain complex Unicode characters and _not_ the document
  1314. // that was deleted.
  1315. {
  1316. NSMutableArray<NSString *> *querySnapshot2ExpectedDocumentIds =
  1317. [NSMutableArray arrayWithArray:testDocIds];
  1318. [querySnapshot2ExpectedDocumentIds removeObject:documentToDelete.documentID];
  1319. XCTAssertEqualObjects(
  1320. [FIRQuerySnapshotGetIDs(querySnapshot2) sortedArrayUsingComparator:sortComparator],
  1321. [querySnapshot2ExpectedDocumentIds sortedArrayUsingComparator:sortComparator],
  1322. @"querySnapshot2 has the wrong documents");
  1323. }
  1324. // Verify that Watch sent an existence filter with the correct counts.
  1325. XCTAssertEqual(existenceFilterMismatches.count, 1u,
  1326. @"Watch should have sent exactly 1 existence filter");
  1327. FSTTestingHooksExistenceFilterMismatchInfo *existenceFilterMismatchInfo =
  1328. existenceFilterMismatches[0];
  1329. XCTAssertEqual(existenceFilterMismatchInfo.localCacheCount, (int)testDocIds.count);
  1330. XCTAssertEqual(existenceFilterMismatchInfo.existenceFilterCount, (int)testDocIds.count - 1);
  1331. // Verify that Watch sent a valid bloom filter.
  1332. FSTTestingHooksBloomFilter *bloomFilter = existenceFilterMismatchInfo.bloomFilter;
  1333. XCTAssertNotNil(bloomFilter, "Watch should have included a bloom filter in the existence filter");
  1334. // The bloom filter application should statistically be successful almost every time; the _only_
  1335. // time when it would _not_ be successful is if there is a false positive when testing for
  1336. // 'DocumentToDelete' in the bloom filter. So verify that the bloom filter application is
  1337. // successful, unless there was a false positive.
  1338. BOOL isFalsePositive = [bloomFilter mightContain:documentToDelete];
  1339. XCTAssertEqual(bloomFilter.applied, !isFalsePositive);
  1340. // Verify that the bloom filter contains the document paths with complex Unicode characters.
  1341. for (FIRDocumentSnapshot *documentSnapshot in querySnapshot2.documents) {
  1342. XCTAssertTrue([bloomFilter mightContain:documentSnapshot.reference],
  1343. @"The bloom filter should contain %@", documentSnapshot.documentID);
  1344. }
  1345. }
  1346. @end