FIRPipelineBridge.mm 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  1. /*
  2. * Copyright 2025 Google LLC
  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 "FIRPipelineBridge.h"
  17. #import <FirebaseCore/FIRTimestamp.h>
  18. #include <memory>
  19. #import "Firestore/Source/API/FIRCollectionReference+Internal.h"
  20. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  21. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  22. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  23. #import "Firestore/Source/API/FIRListenerRegistration+Internal.h"
  24. #import "Firestore/Source/API/FIRPipelineBridge+Internal.h"
  25. #import "Firestore/Source/API/FIRQuery+Internal.h"
  26. #import "Firestore/Source/API/FIRSnapshotMetadata+Internal.h"
  27. #import "Firestore/Source/API/FSTUserDataReader.h"
  28. #import "Firestore/Source/API/FSTUserDataWriter.h"
  29. #import "Firestore/Source/API/converters.h"
  30. #import "Firestore/Source/Public/FirebaseFirestore/FIRVectorValue.h"
  31. #include "Firestore/Protos/nanopb/google/firestore/v1/document.nanopb.h"
  32. #include "Firestore/core/src/api/aggregate_expressions.h"
  33. #include "Firestore/core/src/api/document_reference.h"
  34. #include "Firestore/core/src/api/expressions.h"
  35. #include "Firestore/core/src/api/ordering.h"
  36. #include "Firestore/core/src/api/pipeline.h"
  37. #include "Firestore/core/src/api/pipeline_result.h"
  38. #include "Firestore/core/src/api/pipeline_result_change.h"
  39. #include "Firestore/core/src/api/pipeline_snapshot.h"
  40. #include "Firestore/core/src/api/query_listener_registration.h"
  41. #include "Firestore/core/src/api/realtime_pipeline.h"
  42. #include "Firestore/core/src/api/realtime_pipeline_snapshot.h"
  43. #include "Firestore/core/src/api/snapshot_metadata.h"
  44. #include "Firestore/core/src/api/stages.h"
  45. #include "Firestore/core/src/core/event_listener.h"
  46. #include "Firestore/core/src/core/firestore_client.h"
  47. #include "Firestore/core/src/core/listen_options.h"
  48. #include "Firestore/core/src/core/view_snapshot.h"
  49. #include "Firestore/core/src/util/comparison.h"
  50. #include "Firestore/core/src/util/error_apple.h"
  51. #include "Firestore/core/src/util/status.h"
  52. #include "Firestore/core/src/util/string_apple.h"
  53. using firebase::firestore::api::AddFields;
  54. using firebase::firestore::api::AggregateFunction;
  55. using firebase::firestore::api::AggregateStage;
  56. using firebase::firestore::api::CollectionGroupSource;
  57. using firebase::firestore::api::CollectionSource;
  58. using firebase::firestore::api::Constant;
  59. using firebase::firestore::api::DatabaseSource;
  60. using firebase::firestore::api::DistinctStage;
  61. using firebase::firestore::api::DocumentChange;
  62. using firebase::firestore::api::DocumentReference;
  63. using firebase::firestore::api::DocumentsSource;
  64. using firebase::firestore::api::Expr;
  65. using firebase::firestore::api::Field;
  66. using firebase::firestore::api::FindNearestStage;
  67. using firebase::firestore::api::FunctionExpr;
  68. using firebase::firestore::api::LimitStage;
  69. using firebase::firestore::api::MakeFIRTimestamp;
  70. using firebase::firestore::api::OffsetStage;
  71. using firebase::firestore::api::Ordering;
  72. using firebase::firestore::api::Pipeline;
  73. using firebase::firestore::api::PipelineResultChange;
  74. using firebase::firestore::api::QueryListenerRegistration;
  75. using firebase::firestore::api::RawStage;
  76. using firebase::firestore::api::RealtimePipeline;
  77. using firebase::firestore::api::RealtimePipelineSnapshot;
  78. using firebase::firestore::api::RemoveFieldsStage;
  79. using firebase::firestore::api::ReplaceWith;
  80. using firebase::firestore::api::Sample;
  81. using firebase::firestore::api::SelectStage;
  82. using firebase::firestore::api::SnapshotMetadata;
  83. using firebase::firestore::api::SortStage;
  84. using firebase::firestore::api::Union;
  85. using firebase::firestore::api::Unnest;
  86. using firebase::firestore::api::Where;
  87. using firebase::firestore::core::EventListener;
  88. using firebase::firestore::core::ViewSnapshot;
  89. using firebase::firestore::model::DeepClone;
  90. using firebase::firestore::model::FieldPath;
  91. using firebase::firestore::nanopb::MakeSharedMessage;
  92. using firebase::firestore::nanopb::SharedMessage;
  93. using firebase::firestore::util::ComparisonResult;
  94. using firebase::firestore::util::MakeCallback;
  95. using firebase::firestore::util::MakeNSString;
  96. using firebase::firestore::util::MakeString;
  97. using firebase::firestore::util::ThrowInvalidArgument;
  98. NS_ASSUME_NONNULL_BEGIN
  99. inline std::string EnsureLeadingSlash(const std::string &path) {
  100. if (!path.empty() && path[0] == '/') {
  101. return path;
  102. }
  103. return "/" + path;
  104. }
  105. @implementation FIRExprBridge
  106. @end
  107. @implementation FIRFieldBridge {
  108. FIRFieldPath *field_path;
  109. std::shared_ptr<Field> field;
  110. }
  111. - (id)initWithName:(NSString *)name {
  112. self = [super init];
  113. if (self) {
  114. field_path = [FIRFieldPath pathWithDotSeparatedString:name];
  115. field = std::make_shared<Field>([field_path internalValue].CanonicalString());
  116. }
  117. return self;
  118. }
  119. - (id)initWithPath:(FIRFieldPath *)path {
  120. self = [super init];
  121. if (self) {
  122. field_path = path;
  123. field = std::make_shared<Field>([field_path internalValue].CanonicalString());
  124. }
  125. return self;
  126. }
  127. - (std::shared_ptr<api::Expr>)cppExprWithReader:(FSTUserDataReader *)reader {
  128. return field;
  129. }
  130. - (NSString *)field_name {
  131. return MakeNSString([field_path internalValue].CanonicalString());
  132. }
  133. @end
  134. @implementation FIRConstantBridge {
  135. std::shared_ptr<Constant> cpp_constant;
  136. id _input;
  137. Boolean isUserDataRead;
  138. }
  139. - (id)init:(id)input {
  140. self = [super init];
  141. _input = input;
  142. isUserDataRead = NO;
  143. return self;
  144. }
  145. - (std::shared_ptr<api::Expr>)cppExprWithReader:(FSTUserDataReader *)reader {
  146. if (!isUserDataRead) {
  147. cpp_constant = std::make_shared<Constant>([reader parsedQueryValue:_input]);
  148. }
  149. isUserDataRead = YES;
  150. return cpp_constant;
  151. }
  152. @end
  153. @implementation FIRFunctionExprBridge {
  154. std::shared_ptr<FunctionExpr> cpp_function;
  155. NSString *_name;
  156. NSArray<FIRExprBridge *> *_args;
  157. Boolean isUserDataRead;
  158. }
  159. - (nonnull id)initWithName:(NSString *)name Args:(nonnull NSArray<FIRExprBridge *> *)args {
  160. self = [super init];
  161. _name = name;
  162. _args = args;
  163. isUserDataRead = NO;
  164. return self;
  165. }
  166. - (std::shared_ptr<api::Expr>)cppExprWithReader:(FSTUserDataReader *)reader {
  167. if (!isUserDataRead) {
  168. std::vector<std::shared_ptr<Expr>> cpp_args;
  169. for (FIRExprBridge *arg in _args) {
  170. cpp_args.push_back([arg cppExprWithReader:reader]);
  171. }
  172. cpp_function = std::make_shared<FunctionExpr>(MakeString(_name), std::move(cpp_args));
  173. }
  174. isUserDataRead = YES;
  175. return cpp_function;
  176. }
  177. @end
  178. @implementation FIRAggregateFunctionBridge {
  179. std::shared_ptr<AggregateFunction> cpp_function;
  180. NSString *_name;
  181. NSArray<FIRExprBridge *> *_args;
  182. Boolean isUserDataRead;
  183. }
  184. - (nonnull id)initWithName:(NSString *)name Args:(nonnull NSArray<FIRExprBridge *> *)args {
  185. _name = name;
  186. _args = args;
  187. isUserDataRead = NO;
  188. return self;
  189. }
  190. - (std::shared_ptr<AggregateFunction>)cppExprWithReader:(FSTUserDataReader *)reader {
  191. if (!isUserDataRead) {
  192. std::vector<std::shared_ptr<Expr>> cpp_args;
  193. for (FIRExprBridge *arg in _args) {
  194. cpp_args.push_back([arg cppExprWithReader:reader]);
  195. }
  196. cpp_function = std::make_shared<AggregateFunction>(MakeString(_name), std::move(cpp_args));
  197. }
  198. isUserDataRead = YES;
  199. return cpp_function;
  200. }
  201. @end
  202. @implementation FIROrderingBridge {
  203. std::unique_ptr<Ordering> cpp_ordering;
  204. NSString *_direction;
  205. FIRExprBridge *_expr;
  206. Boolean isUserDataRead;
  207. }
  208. - (nonnull id)initWithExpr:(FIRExprBridge *)expr Direction:(NSString *)direction {
  209. _expr = expr;
  210. _direction = direction;
  211. isUserDataRead = NO;
  212. return self;
  213. }
  214. - (Ordering)cppOrderingWithReader:(FSTUserDataReader *)reader {
  215. if (!isUserDataRead) {
  216. cpp_ordering = std::make_unique<Ordering>(
  217. [_expr cppExprWithReader:reader], Ordering::DirectionFromString(MakeString(_direction)));
  218. }
  219. isUserDataRead = YES;
  220. return *cpp_ordering;
  221. }
  222. @end
  223. @implementation FIRStageBridge
  224. - (NSString *)name {
  225. [NSException raise:NSInternalInconsistencyException
  226. format:@"You must override %@ in a subclass", NSStringFromSelector(_cmd)];
  227. return nil;
  228. }
  229. @end
  230. @implementation FIRCollectionSourceStageBridge {
  231. std::shared_ptr<CollectionSource> collection_source;
  232. }
  233. - (id)initWithRef:(FIRCollectionReference *)ref firestore:(FIRFirestore *)db {
  234. self = [super init];
  235. if (self) {
  236. if (ref.firestore.databaseID.CompareTo(db.databaseID) != ComparisonResult::Same) {
  237. ThrowInvalidArgument(
  238. "Invalid CollectionReference. The project ID (\"%s\") or the database (\"%s\") does not "
  239. "match "
  240. "the project ID (\"%s\") and database (\"%s\") of the target database of this Pipeline.",
  241. ref.firestore.databaseID.project_id(), ref.firestore.databaseID.database_id(),
  242. db.databaseID.project_id(), db.databaseID.project_id());
  243. }
  244. collection_source =
  245. std::make_shared<CollectionSource>(EnsureLeadingSlash(MakeString(ref.path)));
  246. }
  247. return self;
  248. }
  249. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  250. return collection_source;
  251. }
  252. - (id)initWithCppStage:(std::shared_ptr<const api::CollectionSource>)stage {
  253. self = [super init];
  254. if (self) {
  255. collection_source = std::const_pointer_cast<api::CollectionSource>(stage);
  256. }
  257. return self;
  258. }
  259. - (NSString *)name {
  260. return @"collection";
  261. }
  262. @end
  263. @implementation FIRDatabaseSourceStageBridge {
  264. std::shared_ptr<DatabaseSource> cpp_database_source;
  265. }
  266. - (id)init {
  267. self = [super init];
  268. if (self) {
  269. cpp_database_source = std::make_shared<DatabaseSource>();
  270. }
  271. return self;
  272. }
  273. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  274. return cpp_database_source;
  275. }
  276. - (id)initWithCppStage:(std::shared_ptr<const api::DatabaseSource>)stage {
  277. self = [super init];
  278. if (self) {
  279. cpp_database_source = std::const_pointer_cast<api::DatabaseSource>(stage);
  280. }
  281. return self;
  282. }
  283. - (NSString *)name {
  284. return @"database";
  285. }
  286. @end
  287. @implementation FIRCollectionGroupSourceStageBridge {
  288. std::shared_ptr<CollectionGroupSource> cpp_collection_group_source;
  289. }
  290. - (id)initWithCollectionId:(NSString *)id {
  291. self = [super init];
  292. if (self) {
  293. cpp_collection_group_source = std::make_shared<CollectionGroupSource>(MakeString(id));
  294. }
  295. return self;
  296. }
  297. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  298. return cpp_collection_group_source;
  299. }
  300. - (id)initWithCppStage:(std::shared_ptr<const api::CollectionGroupSource>)stage {
  301. self = [super init];
  302. if (self) {
  303. cpp_collection_group_source = std::const_pointer_cast<api::CollectionGroupSource>(stage);
  304. }
  305. return self;
  306. }
  307. - (NSString *)name {
  308. return @"collection_group";
  309. }
  310. @end
  311. @implementation FIRDocumentsSourceStageBridge {
  312. std::shared_ptr<DocumentsSource> cpp_document_source;
  313. }
  314. - (id)initWithDocuments:(NSArray<FIRDocumentReference *> *)documents firestore:(FIRFirestore *)db {
  315. self = [super init];
  316. if (self) {
  317. std::vector<std::string> cpp_documents;
  318. for (FIRDocumentReference *doc in documents) {
  319. if (doc.firestore.databaseID.CompareTo(db.databaseID) != ComparisonResult::Same) {
  320. ThrowInvalidArgument("Invalid DocumentReference. The project ID (\"%s\") or the database "
  321. "(\"%s\") does not match "
  322. "the project ID (\"%s\") and database (\"%s\") of the target database "
  323. "of this Pipeline.",
  324. doc.firestore.databaseID.project_id(),
  325. doc.firestore.databaseID.database_id(), db.databaseID.project_id(),
  326. db.databaseID.project_id());
  327. }
  328. cpp_documents.push_back(EnsureLeadingSlash(MakeString(doc.path)));
  329. }
  330. cpp_document_source = std::make_shared<DocumentsSource>(std::move(cpp_documents));
  331. }
  332. return self;
  333. }
  334. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  335. return cpp_document_source;
  336. }
  337. - (id)initWithCppStage:(std::shared_ptr<const api::DocumentsSource>)stage {
  338. self = [super init];
  339. if (self) {
  340. cpp_document_source = std::const_pointer_cast<api::DocumentsSource>(stage);
  341. }
  342. return self;
  343. }
  344. - (NSString *)name {
  345. return @"documents";
  346. }
  347. @end
  348. @implementation FIRWhereStageBridge {
  349. FIRExprBridge *_exprBridge;
  350. Boolean isUserDataRead;
  351. std::shared_ptr<Where> cpp_where;
  352. }
  353. - (id)initWithExpr:(FIRExprBridge *)expr {
  354. self = [super init];
  355. if (self) {
  356. _exprBridge = expr;
  357. isUserDataRead = NO;
  358. }
  359. return self;
  360. }
  361. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  362. if (!isUserDataRead) {
  363. cpp_where = std::make_shared<Where>([_exprBridge cppExprWithReader:reader]);
  364. }
  365. isUserDataRead = YES;
  366. return cpp_where;
  367. }
  368. - (id)initWithCppStage:(std::shared_ptr<const api::Where>)stage {
  369. self = [super init];
  370. if (self) {
  371. cpp_where = std::const_pointer_cast<api::Where>(stage);
  372. isUserDataRead = YES;
  373. }
  374. return self;
  375. }
  376. - (NSString *)name {
  377. return @"where";
  378. }
  379. @end
  380. @implementation FIRLimitStageBridge {
  381. Boolean isUserDataRead;
  382. std::shared_ptr<LimitStage> cpp_limit_stage;
  383. int32_t limit;
  384. }
  385. - (id)initWithLimit:(NSInteger)value {
  386. self = [super init];
  387. if (self) {
  388. isUserDataRead = NO;
  389. limit = static_cast<int32_t>(value);
  390. }
  391. return self;
  392. }
  393. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  394. if (!isUserDataRead) {
  395. cpp_limit_stage = std::make_shared<LimitStage>(limit);
  396. }
  397. isUserDataRead = YES;
  398. return cpp_limit_stage;
  399. }
  400. - (id)initWithCppStage:(std::shared_ptr<const api::LimitStage>)stage {
  401. self = [super init];
  402. if (self) {
  403. cpp_limit_stage = std::const_pointer_cast<api::LimitStage>(stage);
  404. isUserDataRead = YES;
  405. }
  406. return self;
  407. }
  408. - (NSString *)name {
  409. return @"limit";
  410. }
  411. @end
  412. @implementation FIROffsetStageBridge {
  413. Boolean isUserDataRead;
  414. std::shared_ptr<OffsetStage> cpp_offset_stage;
  415. int32_t offset;
  416. }
  417. - (id)initWithOffset:(NSInteger)value {
  418. self = [super init];
  419. if (self) {
  420. isUserDataRead = NO;
  421. offset = static_cast<int32_t>(value);
  422. }
  423. return self;
  424. }
  425. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  426. if (!isUserDataRead) {
  427. cpp_offset_stage = std::make_shared<OffsetStage>(offset);
  428. }
  429. isUserDataRead = YES;
  430. return cpp_offset_stage;
  431. }
  432. - (id)initWithCppStage:(std::shared_ptr<const api::OffsetStage>)stage {
  433. self = [super init];
  434. if (self) {
  435. cpp_offset_stage = std::const_pointer_cast<api::OffsetStage>(stage);
  436. isUserDataRead = YES;
  437. }
  438. return self;
  439. }
  440. - (NSString *)name {
  441. return @"offset";
  442. }
  443. @end
  444. // TBD
  445. @implementation FIRAddFieldsStageBridge {
  446. NSDictionary<NSString *, FIRExprBridge *> *_fields;
  447. Boolean isUserDataRead;
  448. std::shared_ptr<AddFields> cpp_add_fields;
  449. }
  450. - (id)initWithFields:(NSDictionary<NSString *, FIRExprBridge *> *)fields {
  451. self = [super init];
  452. if (self) {
  453. _fields = fields;
  454. isUserDataRead = NO;
  455. }
  456. return self;
  457. }
  458. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  459. if (!isUserDataRead) {
  460. std::unordered_map<std::string, std::shared_ptr<Expr>> cpp_fields;
  461. for (NSString *key in _fields) {
  462. cpp_fields[MakeString(key)] = [_fields[key] cppExprWithReader:reader];
  463. }
  464. cpp_add_fields = std::make_shared<AddFields>(std::move(cpp_fields));
  465. }
  466. isUserDataRead = YES;
  467. return cpp_add_fields;
  468. }
  469. - (NSString *)name {
  470. return @"add_fields";
  471. }
  472. @end
  473. @implementation FIRRemoveFieldsStageBridge {
  474. NSArray<NSString *> *_fields;
  475. Boolean isUserDataRead;
  476. std::shared_ptr<RemoveFieldsStage> cpp_remove_fields;
  477. }
  478. - (id)initWithFields:(NSArray<id> *)fields {
  479. self = [super init];
  480. if (self) {
  481. _fields = fields;
  482. isUserDataRead = NO;
  483. }
  484. return self;
  485. }
  486. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  487. if (!isUserDataRead) {
  488. std::vector<Field> cpp_fields;
  489. for (id field in _fields) {
  490. cpp_fields.push_back(Field(MakeString(field)));
  491. }
  492. cpp_remove_fields = std::make_shared<RemoveFieldsStage>(std::move(cpp_fields));
  493. }
  494. isUserDataRead = YES;
  495. return cpp_remove_fields;
  496. }
  497. - (NSString *)name {
  498. return @"remove_fields";
  499. }
  500. @end
  501. @implementation FIRSelectStageBridge {
  502. NSDictionary<NSString *, FIRExprBridge *> *_selections;
  503. Boolean isUserDataRead;
  504. std::shared_ptr<SelectStage> cpp_select;
  505. }
  506. - (id)initWithSelections:(NSDictionary<NSString *, FIRExprBridge *> *)selections {
  507. self = [super init];
  508. if (self) {
  509. _selections = selections;
  510. isUserDataRead = NO;
  511. }
  512. return self;
  513. }
  514. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  515. if (!isUserDataRead) {
  516. std::unordered_map<std::string, std::shared_ptr<Expr>> cpp_selections;
  517. for (NSString *key in _selections) {
  518. cpp_selections[MakeString(key)] = [_selections[key] cppExprWithReader:reader];
  519. }
  520. cpp_select = std::make_shared<SelectStage>(std::move(cpp_selections));
  521. }
  522. isUserDataRead = YES;
  523. return cpp_select;
  524. }
  525. - (NSString *)name {
  526. return @"select";
  527. }
  528. @end
  529. @implementation FIRDistinctStageBridge {
  530. NSDictionary<NSString *, FIRExprBridge *> *_groups;
  531. Boolean isUserDataRead;
  532. std::shared_ptr<DistinctStage> cpp_distinct;
  533. }
  534. - (id)initWithGroups:(NSDictionary<NSString *, FIRExprBridge *> *)groups {
  535. self = [super init];
  536. if (self) {
  537. _groups = groups;
  538. isUserDataRead = NO;
  539. }
  540. return self;
  541. }
  542. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  543. if (!isUserDataRead) {
  544. std::unordered_map<std::string, std::shared_ptr<Expr>> cpp_groups;
  545. for (NSString *key in _groups) {
  546. cpp_groups[MakeString(key)] = [_groups[key] cppExprWithReader:reader];
  547. }
  548. cpp_distinct = std::make_shared<DistinctStage>(std::move(cpp_groups));
  549. }
  550. isUserDataRead = YES;
  551. return cpp_distinct;
  552. }
  553. - (NSString *)name {
  554. return @"distinct";
  555. }
  556. @end
  557. @implementation FIRAggregateStageBridge {
  558. NSDictionary<NSString *, FIRAggregateFunctionBridge *> *_accumulators;
  559. NSDictionary<NSString *, FIRExprBridge *> *_groups;
  560. Boolean isUserDataRead;
  561. std::shared_ptr<AggregateStage> cpp_aggregate;
  562. }
  563. - (id)initWithAccumulators:(NSDictionary<NSString *, FIRAggregateFunctionBridge *> *)accumulators
  564. groups:(NSDictionary<NSString *, FIRExprBridge *> *)groups {
  565. self = [super init];
  566. if (self) {
  567. _accumulators = accumulators;
  568. _groups = groups;
  569. isUserDataRead = NO;
  570. }
  571. return self;
  572. }
  573. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  574. if (!isUserDataRead) {
  575. std::unordered_map<std::string, std::shared_ptr<AggregateFunction>> cpp_accumulators;
  576. for (NSString *key in _accumulators) {
  577. cpp_accumulators[MakeString(key)] = [_accumulators[key] cppExprWithReader:reader];
  578. }
  579. std::unordered_map<std::string, std::shared_ptr<Expr>> cpp_groups;
  580. for (NSString *key in _groups) {
  581. cpp_groups[MakeString(key)] = [_groups[key] cppExprWithReader:reader];
  582. }
  583. cpp_aggregate =
  584. std::make_shared<AggregateStage>(std::move(cpp_accumulators), std::move(cpp_groups));
  585. }
  586. isUserDataRead = YES;
  587. return cpp_aggregate;
  588. }
  589. - (NSString *)name {
  590. return @"aggregate";
  591. }
  592. @end
  593. @implementation FIRFindNearestStageBridge {
  594. FIRFieldBridge *_field;
  595. FIRVectorValue *_vectorValue;
  596. NSString *_distanceMeasure;
  597. NSNumber *_limit;
  598. FIRExprBridge *_Nullable _distanceField;
  599. Boolean isUserDataRead;
  600. std::shared_ptr<FindNearestStage> cpp_find_nearest;
  601. }
  602. - (id)initWithField:(FIRFieldBridge *)field
  603. vectorValue:(FIRVectorValue *)vectorValue
  604. distanceMeasure:(NSString *)distanceMeasure
  605. limit:(NSNumber *_Nullable)limit
  606. distanceField:(FIRExprBridge *_Nullable)distanceField {
  607. self = [super init];
  608. if (self) {
  609. _field = field;
  610. _vectorValue = vectorValue;
  611. _distanceMeasure = distanceMeasure;
  612. _limit = limit;
  613. _distanceField = distanceField;
  614. isUserDataRead = NO;
  615. }
  616. return self;
  617. }
  618. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  619. if (!isUserDataRead) {
  620. std::unordered_map<std::string, firebase::firestore::google_firestore_v1_Value> optional_value;
  621. if (_limit) {
  622. optional_value.emplace(std::make_pair(
  623. std::string("limit"), *DeepClone(*[reader parsedQueryValue:_limit]).release()));
  624. }
  625. if (_distanceField) {
  626. std::shared_ptr<Expr> cpp_distance_field = [_distanceField cppExprWithReader:reader];
  627. optional_value.emplace(
  628. std::make_pair(std::string("distance_field"), cpp_distance_field->to_proto()));
  629. }
  630. FindNearestStage::DistanceMeasure::Measure measure_enum;
  631. if ([_distanceMeasure isEqualToString:@"cosine"]) {
  632. measure_enum = FindNearestStage::DistanceMeasure::COSINE;
  633. } else if ([_distanceMeasure isEqualToString:@"dot_product"]) {
  634. measure_enum = FindNearestStage::DistanceMeasure::DOT_PRODUCT;
  635. } else {
  636. measure_enum = FindNearestStage::DistanceMeasure::EUCLIDEAN;
  637. }
  638. cpp_find_nearest = std::make_shared<FindNearestStage>(
  639. [_field cppExprWithReader:reader], [reader parsedQueryValue:_vectorValue],
  640. FindNearestStage::DistanceMeasure(measure_enum), optional_value);
  641. }
  642. isUserDataRead = YES;
  643. return cpp_find_nearest;
  644. }
  645. - (NSString *)name {
  646. return @"find_nearest";
  647. }
  648. @end
  649. @implementation FIRSorStageBridge {
  650. NSArray<FIROrderingBridge *> *_orderings;
  651. Boolean isUserDataRead;
  652. std::shared_ptr<SortStage> cpp_sort;
  653. }
  654. - (id)initWithOrderings:(NSArray<id> *)orderings {
  655. self = [super init];
  656. if (self) {
  657. _orderings = orderings;
  658. isUserDataRead = NO;
  659. }
  660. return self;
  661. }
  662. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  663. if (!isUserDataRead) {
  664. std::vector<Ordering> cpp_orderings;
  665. for (FIROrderingBridge *ordering in _orderings) {
  666. cpp_orderings.push_back([ordering cppOrderingWithReader:reader]);
  667. }
  668. cpp_sort = std::make_shared<SortStage>(std::move(cpp_orderings));
  669. }
  670. isUserDataRead = YES;
  671. return cpp_sort;
  672. }
  673. - (id)initWithCppStage:(std::shared_ptr<const api::SortStage>)stage {
  674. self = [super init];
  675. if (self) {
  676. cpp_sort = std::const_pointer_cast<api::SortStage>(stage);
  677. isUserDataRead = YES;
  678. }
  679. return self;
  680. }
  681. - (NSString *)name {
  682. return @"sort";
  683. }
  684. @end
  685. @implementation FIRReplaceWithStageBridge {
  686. FIRExprBridge *_expr;
  687. Boolean isUserDataRead;
  688. std::shared_ptr<ReplaceWith> cpp_replace_with;
  689. }
  690. - (id)initWithExpr:(FIRExprBridge *)expr {
  691. self = [super init];
  692. if (self) {
  693. _expr = expr;
  694. isUserDataRead = NO;
  695. }
  696. return self;
  697. }
  698. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  699. if (!isUserDataRead) {
  700. cpp_replace_with = std::make_shared<ReplaceWith>([_expr cppExprWithReader:reader]);
  701. }
  702. isUserDataRead = YES;
  703. return cpp_replace_with;
  704. }
  705. - (NSString *)name {
  706. return @"replace_with";
  707. }
  708. @end
  709. @implementation FIRSampleStageBridge {
  710. int64_t _count;
  711. double _percentage;
  712. Boolean isUserDataRead;
  713. NSString *type;
  714. std::shared_ptr<Sample> cpp_sample;
  715. }
  716. - (id)initWithCount:(int64_t)count {
  717. self = [super init];
  718. if (self) {
  719. _count = count;
  720. _percentage = 0;
  721. type = @"count";
  722. isUserDataRead = NO;
  723. }
  724. return self;
  725. }
  726. - (id)initWithPercentage:(double)percentage {
  727. self = [super init];
  728. if (self) {
  729. _percentage = percentage;
  730. _count = 0;
  731. type = @"percentage";
  732. isUserDataRead = NO;
  733. }
  734. return self;
  735. }
  736. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  737. if (!isUserDataRead) {
  738. if ([type isEqualToString:@"count"]) {
  739. cpp_sample =
  740. std::make_shared<Sample>(Sample::SampleMode(Sample::SampleMode::DOCUMENTS), _count, 0);
  741. } else {
  742. cpp_sample =
  743. std::make_shared<Sample>(Sample::SampleMode(Sample::SampleMode::PERCENT), 0, _percentage);
  744. }
  745. }
  746. isUserDataRead = YES;
  747. return cpp_sample;
  748. }
  749. - (NSString *)name {
  750. return @"sample";
  751. }
  752. @end
  753. @implementation FIRUnionStageBridge {
  754. FIRPipelineBridge *_other;
  755. Boolean isUserDataRead;
  756. std::shared_ptr<Union> cpp_union_stage;
  757. }
  758. - (id)initWithOther:(FIRPipelineBridge *)other {
  759. self = [super init];
  760. if (self) {
  761. _other = other;
  762. isUserDataRead = NO;
  763. }
  764. return self;
  765. }
  766. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  767. if (!isUserDataRead) {
  768. cpp_union_stage = std::make_shared<Union>([_other cppPipelineWithReader:reader]);
  769. }
  770. isUserDataRead = YES;
  771. return cpp_union_stage;
  772. }
  773. - (NSString *)name {
  774. return @"union";
  775. }
  776. @end
  777. @implementation FIRUnnestStageBridge {
  778. FIRExprBridge *_field;
  779. FIRExprBridge *_Nullable _index_field;
  780. FIRExprBridge *_alias;
  781. Boolean isUserDataRead;
  782. std::shared_ptr<Unnest> cpp_unnest;
  783. }
  784. - (id)initWithField:(FIRExprBridge *)field
  785. alias:(FIRExprBridge *)alias
  786. indexField:(FIRExprBridge *_Nullable)index_field {
  787. self = [super init];
  788. if (self) {
  789. _field = field;
  790. _alias = alias;
  791. _index_field = index_field;
  792. isUserDataRead = NO;
  793. }
  794. return self;
  795. }
  796. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  797. if (!isUserDataRead) {
  798. absl::optional<std::shared_ptr<Expr>> cpp_index_field;
  799. if (_index_field != nil) {
  800. cpp_index_field = [_index_field cppExprWithReader:reader];
  801. } else {
  802. cpp_index_field = absl::nullopt;
  803. }
  804. cpp_unnest = std::make_shared<Unnest>([_field cppExprWithReader:reader],
  805. [_alias cppExprWithReader:reader], cpp_index_field);
  806. }
  807. isUserDataRead = YES;
  808. return cpp_unnest;
  809. }
  810. - (NSString *)name {
  811. return @"unnest";
  812. }
  813. @end
  814. @implementation FIRRawStageBridge {
  815. NSString *_name;
  816. NSArray<id> *_params;
  817. NSDictionary<NSString *, FIRExprBridge *> *_Nullable _options;
  818. Boolean isUserDataRead;
  819. std::shared_ptr<RawStage> cpp_generic_stage;
  820. }
  821. - (id)initWithName:(NSString *)name
  822. params:(NSArray<id> *)params
  823. options:(NSDictionary<NSString *, FIRExprBridge *> *_Nullable)options {
  824. self = [super init];
  825. if (self) {
  826. _name = name;
  827. _params = params;
  828. _options = options;
  829. isUserDataRead = NO;
  830. }
  831. return self;
  832. }
  833. - (firebase::firestore::google_firestore_v1_Value)convertIdToV1Value:(id)value
  834. reader:(FSTUserDataReader *)reader {
  835. if ([value isKindOfClass:[FIRExprBridge class]]) {
  836. return [((FIRExprBridge *)value) cppExprWithReader:reader]->to_proto();
  837. } else if ([value isKindOfClass:[FIRAggregateFunctionBridge class]]) {
  838. return [((FIRAggregateFunctionBridge *)value) cppExprWithReader:reader]->to_proto();
  839. } else if ([value isKindOfClass:[NSDictionary class]]) {
  840. NSDictionary<NSString *, id> *dictionary = (NSDictionary<NSString *, id> *)value;
  841. std::unordered_map<std::string, firebase::firestore::google_firestore_v1_Value> cpp_dictionary;
  842. for (NSString *key in dictionary) {
  843. if ([dictionary[key] isKindOfClass:[FIRExprBridge class]]) {
  844. cpp_dictionary[MakeString(key)] =
  845. [((FIRExprBridge *)dictionary[key]) cppExprWithReader:reader]->to_proto();
  846. } else if ([dictionary[key] isKindOfClass:[FIRAggregateFunctionBridge class]]) {
  847. cpp_dictionary[MakeString(key)] =
  848. [((FIRAggregateFunctionBridge *)dictionary[key]) cppExprWithReader:reader]->to_proto();
  849. } else {
  850. ThrowInvalidArgument(
  851. "Dictionary value must be an FIRExprBridge or FIRAggregateFunctionBridge.");
  852. }
  853. }
  854. firebase::firestore::google_firestore_v1_Value result;
  855. result.which_value_type = google_firestore_v1_Value_map_value_tag;
  856. nanopb::SetRepeatedField(
  857. &result.map_value.fields, &result.map_value.fields_count, cpp_dictionary,
  858. [](const std::pair<std::string, firebase::firestore::google_firestore_v1_Value> &entry) {
  859. return firebase::firestore::_google_firestore_v1_MapValue_FieldsEntry{
  860. nanopb::MakeBytesArray(entry.first), entry.second};
  861. });
  862. return result;
  863. } else {
  864. ThrowInvalidArgument("Invalid value to convert to google_firestore_v1_Value.");
  865. }
  866. }
  867. - (std::shared_ptr<api::Stage>)cppStageWithReader:(FSTUserDataReader *)reader {
  868. if (!isUserDataRead) {
  869. std::vector<firebase::firestore::google_firestore_v1_Value> cpp_params;
  870. for (id param in _params) {
  871. cpp_params.push_back([self convertIdToV1Value:param reader:reader]);
  872. }
  873. std::unordered_map<std::string, std::shared_ptr<Expr>> cpp_options;
  874. if (_options) {
  875. for (NSString *key in _options) {
  876. cpp_options[MakeString(key)] = [_options[key] cppExprWithReader:reader];
  877. }
  878. }
  879. cpp_generic_stage = std::make_shared<RawStage>(MakeString(_name), std::move(cpp_params),
  880. std::move(cpp_options));
  881. }
  882. isUserDataRead = YES;
  883. return cpp_generic_stage;
  884. }
  885. - (NSString *)name {
  886. return _name;
  887. }
  888. @end
  889. @interface __FIRPipelineSnapshotBridge ()
  890. @property(nonatomic, strong, readwrite) NSArray<__FIRPipelineResultBridge *> *results;
  891. @end
  892. @implementation __FIRPipelineSnapshotBridge {
  893. absl::optional<api::PipelineSnapshot> snapshot_;
  894. NSMutableArray<__FIRPipelineResultBridge *> *results_;
  895. }
  896. - (id)initWithCppSnapshot:(api::PipelineSnapshot)snapshot {
  897. self = [super init];
  898. if (self) {
  899. snapshot_ = std::move(snapshot);
  900. if (!snapshot_.has_value()) {
  901. results_ = nil;
  902. } else {
  903. NSMutableArray<__FIRPipelineResultBridge *> *results = [NSMutableArray array];
  904. for (auto &result : snapshot_.value().results()) {
  905. [results addObject:[[__FIRPipelineResultBridge alloc]
  906. initWithCppResult:result
  907. db:snapshot_.value().firestore()]];
  908. }
  909. results_ = results;
  910. }
  911. }
  912. return self;
  913. }
  914. - (NSArray<__FIRPipelineResultBridge *> *)results {
  915. return results_;
  916. }
  917. - (FIRTimestamp *)execution_time {
  918. if (!snapshot_.has_value()) {
  919. return nil;
  920. } else {
  921. return MakeFIRTimestamp(snapshot_.value().execution_time().timestamp());
  922. }
  923. }
  924. @end
  925. @implementation __FIRPipelineResultBridge {
  926. api::PipelineResult _result;
  927. std::shared_ptr<api::Firestore> _db;
  928. }
  929. - (nullable FIRDocumentReference *)reference {
  930. if (!_result.internal_key().has_value()) return nil;
  931. return [[FIRDocumentReference alloc] initWithKey:_result.internal_key().value() firestore:_db];
  932. }
  933. - (nullable NSString *)documentID {
  934. if (!_result.document_id().has_value()) {
  935. return nil;
  936. }
  937. return MakeNSString(_result.document_id().value());
  938. }
  939. - (nullable FIRTimestamp *)create_time {
  940. if (!_result.create_time().has_value()) {
  941. return nil;
  942. }
  943. return MakeFIRTimestamp(_result.create_time().value().timestamp());
  944. }
  945. - (nullable FIRTimestamp *)update_time {
  946. if (!_result.update_time().has_value()) {
  947. return nil;
  948. }
  949. return MakeFIRTimestamp(_result.update_time().value().timestamp());
  950. }
  951. - (id)initWithCppResult:(api::PipelineResult)result db:(std::shared_ptr<api::Firestore>)db {
  952. self = [super init];
  953. if (self) {
  954. _result = std::move(result);
  955. _db = std::move(db);
  956. }
  957. return self;
  958. }
  959. - (NSDictionary<NSString *, id> *)data {
  960. return [self dataWithServerTimestampBehavior:FIRServerTimestampBehaviorNone];
  961. }
  962. - (NSDictionary<NSString *, id> *)dataWithServerTimestampBehavior:
  963. (FIRServerTimestampBehavior)serverTimestampBehavior {
  964. absl::optional<firebase::firestore::google_firestore_v1_Value> data =
  965. _result.internal_value()->Get();
  966. if (!data) return [NSDictionary dictionary];
  967. FSTUserDataWriter *dataWriter =
  968. [[FSTUserDataWriter alloc] initWithFirestore:_db
  969. serverTimestampBehavior:serverTimestampBehavior];
  970. NSDictionary<NSString *, id> *dictionary = [dataWriter convertedValue:*data];
  971. NSLog(@"Dictionary contents: %@", dictionary);
  972. return dictionary;
  973. }
  974. - (nullable id)get:(id)field {
  975. return [self get:field serverTimestampBehavior:FIRServerTimestampBehaviorNone];
  976. }
  977. - (nullable id)get:(id)field
  978. serverTimestampBehavior:(FIRServerTimestampBehavior)serverTimestampBehavior {
  979. FieldPath fieldPath;
  980. if ([field isKindOfClass:[NSString class]]) {
  981. fieldPath = FieldPath::FromDotSeparatedString(MakeString(field));
  982. } else if ([field isKindOfClass:[FIRFieldPath class]]) {
  983. fieldPath = ((FIRFieldPath *)field).internalValue;
  984. } else {
  985. ThrowInvalidArgument("Subscript key must be an NSString or FIRFieldPath.");
  986. }
  987. absl::optional<firebase::firestore::google_firestore_v1_Value> fieldValue =
  988. _result.internal_value()->Get(fieldPath);
  989. if (!fieldValue) return nil;
  990. FSTUserDataWriter *dataWriter =
  991. [[FSTUserDataWriter alloc] initWithFirestore:_db
  992. serverTimestampBehavior:serverTimestampBehavior];
  993. return [dataWriter convertedValue:*fieldValue];
  994. }
  995. @end
  996. @implementation __FIRPipelineResultChangeBridge {
  997. api::PipelineResultChange change_;
  998. std::shared_ptr<api::Firestore> db_;
  999. }
  1000. - (FIRDocumentChangeType)type {
  1001. switch (change_.type()) {
  1002. case PipelineResultChange::Type::Added:
  1003. return FIRDocumentChangeTypeAdded;
  1004. case PipelineResultChange::Type::Modified:
  1005. return FIRDocumentChangeTypeModified;
  1006. case PipelineResultChange::Type::Removed:
  1007. return FIRDocumentChangeTypeRemoved;
  1008. }
  1009. HARD_FAIL("Unknown PipelineResultChange::Type: %s", change_.type());
  1010. }
  1011. - (__FIRPipelineResultBridge *)result {
  1012. return [[__FIRPipelineResultBridge alloc] initWithCppResult:change_.result() db:db_];
  1013. }
  1014. - (NSUInteger)oldIndex {
  1015. return change_.old_index() == PipelineResultChange::npos ? NSNotFound : change_.old_index();
  1016. }
  1017. - (NSUInteger)newIndex {
  1018. return change_.new_index() == PipelineResultChange::npos ? NSNotFound : change_.new_index();
  1019. }
  1020. - (id)initWithCppChange:(api::PipelineResultChange)change db:(std::shared_ptr<api::Firestore>)db {
  1021. self = [super init];
  1022. if (self) {
  1023. change_ = std::move(change);
  1024. db_ = std::move(db);
  1025. }
  1026. return self;
  1027. }
  1028. @end
  1029. @implementation FIRPipelineBridge {
  1030. NSArray<FIRStageBridge *> *_stages;
  1031. FIRFirestore *firestore;
  1032. Boolean isUserDataRead;
  1033. std::shared_ptr<Pipeline> cpp_pipeline;
  1034. }
  1035. - (id)initWithStages:(NSArray<FIRStageBridge *> *)stages db:(FIRFirestore *)db {
  1036. _stages = stages;
  1037. firestore = db;
  1038. isUserDataRead = NO;
  1039. return [super init];
  1040. }
  1041. - (void)executeWithCompletion:(void (^)(__FIRPipelineSnapshotBridge *_Nullable result,
  1042. NSError *_Nullable error))completion {
  1043. [self cppPipelineWithReader:firestore.dataReader]->execute(
  1044. [completion](StatusOr<api::PipelineSnapshot> maybe_value) {
  1045. if (maybe_value.ok()) {
  1046. __FIRPipelineSnapshotBridge *bridge = [[__FIRPipelineSnapshotBridge alloc]
  1047. initWithCppSnapshot:std::move(maybe_value).ValueOrDie()];
  1048. completion(bridge, nil);
  1049. } else {
  1050. completion(nil, MakeNSError(std::move(maybe_value).status()));
  1051. }
  1052. });
  1053. }
  1054. - (std::shared_ptr<api::Pipeline>)cppPipelineWithReader:(FSTUserDataReader *)reader {
  1055. if (!isUserDataRead) {
  1056. std::vector<std::shared_ptr<firebase::firestore::api::Stage>> cpp_stages;
  1057. for (FIRStageBridge *stage in _stages) {
  1058. cpp_stages.push_back([stage cppStageWithReader:firestore.dataReader]);
  1059. }
  1060. cpp_pipeline = std::make_shared<Pipeline>(cpp_stages, firestore.wrapped);
  1061. }
  1062. isUserDataRead = YES;
  1063. return cpp_pipeline;
  1064. }
  1065. + (NSArray<FIRStageBridge *> *)createStageBridgesFromQuery:(FIRQuery *)query {
  1066. std::vector<std::shared_ptr<api::EvaluableStage>> evaluable_stages =
  1067. firebase::firestore::core::ToPipelineStages(query.query);
  1068. std::vector<std::shared_ptr<api::Stage>> cpp_stages(evaluable_stages.begin(),
  1069. evaluable_stages.end());
  1070. NSMutableArray<FIRStageBridge *> *stageBridges = [NSMutableArray array];
  1071. for (const auto &cpp_stage_base : cpp_stages) {
  1072. if (auto cpp_stage = std::dynamic_pointer_cast<api::CollectionSource>(cpp_stage_base)) {
  1073. [stageBridges addObject:[[FIRCollectionSourceStageBridge alloc] initWithCppStage:cpp_stage]];
  1074. } else if (auto cpp_stage =
  1075. std::dynamic_pointer_cast<api::CollectionGroupSource>(cpp_stage_base)) {
  1076. [stageBridges
  1077. addObject:[[FIRCollectionGroupSourceStageBridge alloc] initWithCppStage:cpp_stage]];
  1078. } else if (auto cpp_stage = std::dynamic_pointer_cast<api::DocumentsSource>(cpp_stage_base)) {
  1079. [stageBridges addObject:[[FIRDocumentsSourceStageBridge alloc] initWithCppStage:cpp_stage]];
  1080. } else if (auto cpp_stage = std::dynamic_pointer_cast<api::Where>(cpp_stage_base)) {
  1081. [stageBridges addObject:[[FIRWhereStageBridge alloc] initWithCppStage:cpp_stage]];
  1082. } else if (auto cpp_stage = std::dynamic_pointer_cast<api::LimitStage>(cpp_stage_base)) {
  1083. [stageBridges addObject:[[FIRLimitStageBridge alloc] initWithCppStage:cpp_stage]];
  1084. } else if (auto cpp_stage = std::dynamic_pointer_cast<api::SortStage>(cpp_stage_base)) {
  1085. [stageBridges addObject:[[FIRSorStageBridge alloc] initWithCppStage:cpp_stage]];
  1086. } else if (auto cpp_stage = std::dynamic_pointer_cast<api::OffsetStage>(cpp_stage_base)) {
  1087. [stageBridges addObject:[[FIROffsetStageBridge alloc] initWithCppStage:cpp_stage]];
  1088. } else {
  1089. ThrowInvalidArgument(
  1090. "Unknown or unhandled stage type '%s' encountered when converting from FIRQuery.",
  1091. cpp_stage_base->name().c_str());
  1092. }
  1093. }
  1094. return [stageBridges copy];
  1095. }
  1096. @end
  1097. @interface __FIRRealtimePipelineSnapshotBridge ()
  1098. @property(nonatomic, strong, readwrite) NSArray<__FIRPipelineResultBridge *> *results;
  1099. @property(nonatomic, strong, readwrite) NSArray<__FIRPipelineResultChangeBridge *> *changes;
  1100. @end
  1101. @implementation __FIRRealtimePipelineSnapshotBridge {
  1102. absl::optional<api::RealtimePipelineSnapshot> snapshot_;
  1103. NSMutableArray<__FIRPipelineResultBridge *> *results_;
  1104. NSMutableArray<__FIRPipelineResultChangeBridge *> *changes_;
  1105. FIRSnapshotMetadata *_metadata;
  1106. }
  1107. - (id)initWithCppSnapshot:(api::RealtimePipelineSnapshot)snapshot {
  1108. self = [super init];
  1109. if (self) {
  1110. snapshot_ = std::move(snapshot);
  1111. if (!snapshot_.has_value()) {
  1112. results_ = nil;
  1113. } else {
  1114. _metadata =
  1115. [[FIRSnapshotMetadata alloc] initWithMetadata:snapshot_.value().snapshot_metadata()];
  1116. NSMutableArray<__FIRPipelineResultBridge *> *results = [NSMutableArray array];
  1117. for (auto &result : snapshot_.value().view_snapshot().documents()) {
  1118. [results addObject:[[__FIRPipelineResultBridge alloc]
  1119. initWithCppResult:api::PipelineResult(result)
  1120. db:snapshot_.value().firestore()]];
  1121. }
  1122. results_ = results;
  1123. NSMutableArray<__FIRPipelineResultChangeBridge *> *changes = [NSMutableArray array];
  1124. for (auto &change : snapshot_.value().CalculateResultChanges(false)) {
  1125. [changes addObject:[[__FIRPipelineResultChangeBridge alloc]
  1126. initWithCppChange:change
  1127. db:snapshot_.value().firestore()]];
  1128. }
  1129. changes_ = changes;
  1130. }
  1131. }
  1132. return self;
  1133. }
  1134. - (NSArray<__FIRPipelineResultBridge *> *)results {
  1135. return results_;
  1136. }
  1137. - (NSArray<__FIRPipelineResultChangeBridge *> *)changes {
  1138. return changes_;
  1139. }
  1140. - (FIRSnapshotMetadata *)metadata {
  1141. return _metadata;
  1142. }
  1143. @end
  1144. @implementation __FIRPipelineListenOptionsBridge
  1145. - (instancetype)initWithServerTimestampBehavior:(NSString *)serverTimestampBehavior
  1146. includeMetadata:(BOOL)includeMetadata
  1147. source:(FIRListenSource)source {
  1148. // Call the designated initializer of the superclass (NSObject).
  1149. self = [super init];
  1150. if (self) {
  1151. // Assign the passed-in values to the backing instance variables
  1152. // for the readonly properties.
  1153. // We use `copy` here for the string to ensure our object owns an immutable version.
  1154. _serverTimestampBehavior = [serverTimestampBehavior copy];
  1155. _includeMetadata = includeMetadata;
  1156. _source = source;
  1157. }
  1158. return self;
  1159. }
  1160. @end
  1161. @implementation FIRRealtimePipelineBridge {
  1162. NSArray<FIRStageBridge *> *_stages;
  1163. FIRFirestore *firestore;
  1164. std::shared_ptr<api::RealtimePipeline> cpp_pipeline;
  1165. }
  1166. - (id)initWithStages:(NSArray<FIRStageBridge *> *)stages db:(FIRFirestore *)db {
  1167. _stages = stages;
  1168. firestore = db;
  1169. return [super init];
  1170. }
  1171. core::ListenOptions ToListenOptions(__FIRPipelineListenOptionsBridge *_Nullable bridge) {
  1172. // If the bridge object is nil, return a default-constructed ListenOptions.
  1173. if (bridge == nil) {
  1174. return core::ListenOptions::DefaultOptions();
  1175. }
  1176. // 1. Translate include_metadata_changes
  1177. bool include_metadata = bridge.includeMetadata;
  1178. // 2. Translate ListenSource
  1179. core::ListenSource source = core::ListenSource::Default;
  1180. switch (bridge.source) {
  1181. case FIRListenSourceDefault:
  1182. source = core::ListenSource::Default;
  1183. break;
  1184. case FIRListenSourceCache:
  1185. source = core::ListenSource::Cache;
  1186. break;
  1187. }
  1188. // 3. Translate ServerTimestampBehavior
  1189. core::ListenOptions::ServerTimestampBehavior behavior =
  1190. core::ListenOptions::ServerTimestampBehavior::kNone;
  1191. if ([bridge.serverTimestampBehavior isEqual:@"estimate"]) {
  1192. behavior = core::ListenOptions::ServerTimestampBehavior::kEstimate;
  1193. } else if ([bridge.serverTimestampBehavior isEqual:@"previous"]) {
  1194. behavior = core::ListenOptions::ServerTimestampBehavior::kPrevious;
  1195. } else {
  1196. // "none" or any other value defaults to kNone.
  1197. behavior = core::ListenOptions::ServerTimestampBehavior::kNone;
  1198. }
  1199. // 4. Construct the final C++ object using the canonical private constructor.
  1200. // Note: wait_for_sync_when_online is not part of the bridge, so we use 'false'
  1201. // to match the behavior of the existing static factories.
  1202. return core::ListenOptions(
  1203. /*include_query_metadata_changes=*/include_metadata,
  1204. /*include_document_metadata_changes=*/include_metadata,
  1205. /*wait_for_sync_when_online=*/false, source, behavior);
  1206. }
  1207. - (id<FIRListenerRegistration>)
  1208. addSnapshotListenerWithOptions:(__FIRPipelineListenOptionsBridge *)options
  1209. listener:
  1210. (void (^)(__FIRRealtimePipelineSnapshotBridge *_Nullable snapshot,
  1211. NSError *_Nullable error))listener {
  1212. std::shared_ptr<api::Firestore> wrapped_firestore = firestore.wrapped;
  1213. std::vector<std::shared_ptr<firebase::firestore::api::EvaluableStage>> cpp_stages;
  1214. for (FIRStageBridge *stage in _stages) {
  1215. auto evaluable_stage = std::dynamic_pointer_cast<api::EvaluableStage>(
  1216. [stage cppStageWithReader:firestore.dataReader]);
  1217. if (evaluable_stage) {
  1218. cpp_stages.push_back(evaluable_stage);
  1219. } else {
  1220. HARD_FAIL("Failed to convert cpp stage to EvaluableStage for RealtimePipeline");
  1221. }
  1222. }
  1223. cpp_pipeline = std::make_shared<RealtimePipeline>(
  1224. cpp_stages, std::make_unique<remote::Serializer>(wrapped_firestore->database_id()));
  1225. // Convert from ViewSnapshots to RealtimePipelineSnapshots.
  1226. auto view_listener = EventListener<ViewSnapshot>::Create(
  1227. [listener, wrapped_firestore](StatusOr<ViewSnapshot> maybe_snapshot) {
  1228. if (!maybe_snapshot.status().ok()) {
  1229. listener(nil, MakeNSError(maybe_snapshot.status()));
  1230. return;
  1231. }
  1232. ViewSnapshot snapshot = std::move(maybe_snapshot).ValueOrDie();
  1233. SnapshotMetadata metadata(snapshot.has_pending_writes(), snapshot.from_cache());
  1234. listener(
  1235. [[__FIRRealtimePipelineSnapshotBridge alloc]
  1236. initWithCppSnapshot:RealtimePipelineSnapshot(wrapped_firestore, std::move(snapshot),
  1237. std::move(metadata))],
  1238. nil);
  1239. });
  1240. // Call the view_listener on the user Executor.
  1241. auto async_listener = core::AsyncEventListener<ViewSnapshot>::Create(
  1242. wrapped_firestore->client()->user_executor(), std::move(view_listener));
  1243. std::shared_ptr<core::QueryListener> query_listener = wrapped_firestore->client()->ListenToQuery(
  1244. core::QueryOrPipeline(*cpp_pipeline), ToListenOptions(options), async_listener);
  1245. return [[FSTListenerRegistration alloc]
  1246. initWithRegistration:absl::make_unique<QueryListenerRegistration>(wrapped_firestore->client(),
  1247. std::move(async_listener),
  1248. std::move(query_listener))];
  1249. }
  1250. - (std::shared_ptr<api::RealtimePipeline>)cppPipelineWithReader:(FSTUserDataReader *)reader {
  1251. return cpp_pipeline;
  1252. }
  1253. @end
  1254. NS_ASSUME_NONNULL_END