FSTUserDataConverter.mm 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  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 "Firestore/Source/API/FSTUserDataConverter.h"
  17. #include <memory>
  18. #include <utility>
  19. #include <vector>
  20. #import "FIRGeoPoint.h"
  21. #import "FIRTimestamp.h"
  22. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  23. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  24. #import "Firestore/Source/API/FIRFieldValue+Internal.h"
  25. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  26. #import "Firestore/Source/Model/FSTFieldValue.h"
  27. #import "Firestore/Source/Model/FSTMutation.h"
  28. #import "Firestore/Source/Util/FSTAssert.h"
  29. #import "Firestore/Source/Util/FSTUsageValidation.h"
  30. #include "Firestore/core/src/firebase/firestore/model/database_id.h"
  31. #include "Firestore/core/src/firebase/firestore/model/document_key.h"
  32. #include "Firestore/core/src/firebase/firestore/model/field_mask.h"
  33. #include "Firestore/core/src/firebase/firestore/model/field_path.h"
  34. #include "Firestore/core/src/firebase/firestore/model/field_transform.h"
  35. #include "Firestore/core/src/firebase/firestore/model/precondition.h"
  36. #include "Firestore/core/src/firebase/firestore/model/transform_operations.h"
  37. #include "Firestore/core/src/firebase/firestore/util/string_apple.h"
  38. #include "absl/memory/memory.h"
  39. namespace util = firebase::firestore::util;
  40. using firebase::firestore::model::ArrayTransform;
  41. using firebase::firestore::model::DatabaseId;
  42. using firebase::firestore::model::DocumentKey;
  43. using firebase::firestore::model::FieldMask;
  44. using firebase::firestore::model::FieldPath;
  45. using firebase::firestore::model::FieldTransform;
  46. using firebase::firestore::model::Precondition;
  47. using firebase::firestore::model::ServerTimestampTransform;
  48. using firebase::firestore::model::TransformOperation;
  49. NS_ASSUME_NONNULL_BEGIN
  50. static NSString *const RESERVED_FIELD_DESIGNATOR = @"__";
  51. #pragma mark - FSTParsedSetData
  52. @implementation FSTParsedSetData {
  53. FieldMask _fieldMask;
  54. std::vector<FieldTransform> _fieldTransforms;
  55. }
  56. - (instancetype)initWithData:(FSTObjectValue *)data
  57. fieldTransforms:(std::vector<FieldTransform>)fieldTransforms {
  58. self = [super init];
  59. if (self) {
  60. _data = data;
  61. _fieldTransforms = std::move(fieldTransforms);
  62. _isPatch = NO;
  63. }
  64. return self;
  65. }
  66. - (instancetype)initWithData:(FSTObjectValue *)data
  67. fieldMask:(FieldMask)fieldMask
  68. fieldTransforms:(std::vector<FieldTransform>)fieldTransforms {
  69. self = [super init];
  70. if (self) {
  71. _data = data;
  72. _fieldMask = std::move(fieldMask);
  73. _fieldTransforms = std::move(fieldTransforms);
  74. _isPatch = YES;
  75. }
  76. return self;
  77. }
  78. - (const std::vector<FieldTransform> &)fieldTransforms {
  79. return _fieldTransforms;
  80. }
  81. - (NSArray<FSTMutation *> *)mutationsWithKey:(const DocumentKey &)key
  82. precondition:(const Precondition &)precondition {
  83. NSMutableArray<FSTMutation *> *mutations = [NSMutableArray array];
  84. if (self.isPatch) {
  85. [mutations addObject:[[FSTPatchMutation alloc] initWithKey:key
  86. fieldMask:_fieldMask
  87. value:self.data
  88. precondition:precondition]];
  89. } else {
  90. [mutations addObject:[[FSTSetMutation alloc] initWithKey:key
  91. value:self.data
  92. precondition:precondition]];
  93. }
  94. if (!self.fieldTransforms.empty()) {
  95. [mutations addObject:[[FSTTransformMutation alloc] initWithKey:key
  96. fieldTransforms:self.fieldTransforms]];
  97. }
  98. return mutations;
  99. }
  100. @end
  101. #pragma mark - FSTParsedUpdateData
  102. @implementation FSTParsedUpdateData {
  103. FieldMask _fieldMask;
  104. std::vector<FieldTransform> _fieldTransforms;
  105. }
  106. - (instancetype)initWithData:(FSTObjectValue *)data
  107. fieldMask:(FieldMask)fieldMask
  108. fieldTransforms:(std::vector<FieldTransform>)fieldTransforms {
  109. self = [super init];
  110. if (self) {
  111. _data = data;
  112. _fieldMask = std::move(fieldMask);
  113. _fieldTransforms = std::move(fieldTransforms);
  114. }
  115. return self;
  116. }
  117. - (NSArray<FSTMutation *> *)mutationsWithKey:(const DocumentKey &)key
  118. precondition:(const Precondition &)precondition {
  119. NSMutableArray<FSTMutation *> *mutations = [NSMutableArray array];
  120. [mutations addObject:[[FSTPatchMutation alloc] initWithKey:key
  121. fieldMask:self.fieldMask
  122. value:self.data
  123. precondition:precondition]];
  124. if (!self.fieldTransforms.empty()) {
  125. [mutations addObject:[[FSTTransformMutation alloc] initWithKey:key
  126. fieldTransforms:self.fieldTransforms]];
  127. }
  128. return mutations;
  129. }
  130. - (const firebase::firestore::model::FieldMask &)fieldMask {
  131. return _fieldMask;
  132. }
  133. - (const std::vector<FieldTransform> &)fieldTransforms {
  134. return _fieldTransforms;
  135. }
  136. @end
  137. /**
  138. * Represents what type of API method provided the data being parsed; useful for determining which
  139. * error conditions apply during parsing and providing better error messages.
  140. */
  141. typedef NS_ENUM(NSInteger, FSTUserDataSource) {
  142. FSTUserDataSourceSet,
  143. FSTUserDataSourceMergeSet,
  144. FSTUserDataSourceUpdate,
  145. /**
  146. * Indicates the source is a where clause, cursor bound, arrayUnion() element, etc. In particular,
  147. * this will result in [FSTParseContext isWrite] returning NO.
  148. */
  149. FSTUserDataSourceArgument,
  150. };
  151. #pragma mark - FSTParseContext
  152. /**
  153. * A "context" object passed around while parsing user data.
  154. */
  155. @interface FSTParseContext : NSObject
  156. /** Whether or not this context corresponds to an element of an array. */
  157. @property(nonatomic, assign, readonly, getter=isArrayElement) BOOL arrayElement;
  158. /**
  159. * What type of API method provided the data being parsed; useful for determining which error
  160. * conditions apply during parsing and providing better error messages.
  161. */
  162. @property(nonatomic, assign) FSTUserDataSource dataSource;
  163. - (instancetype)init NS_UNAVAILABLE;
  164. /**
  165. * Initializes a FSTParseContext with the given source and path.
  166. *
  167. * @param dataSource Indicates what kind of API method this data came from.
  168. * @param path A path within the object being parsed. This could be an empty path (in which case
  169. * the context represents the root of the data being parsed), or a nonempty path (indicating the
  170. * context represents a nested location within the data).
  171. *
  172. * TODO(b/34871131): We don't support array paths right now, so path can be nullptr to indicate
  173. * the context represents any location within an array (in which case certain features will not work
  174. * and errors will be somewhat compromised).
  175. */
  176. - (instancetype)initWithSource:(FSTUserDataSource)dataSource
  177. path:(std::unique_ptr<FieldPath>)path
  178. arrayElement:(BOOL)arrayElement
  179. fieldTransforms:(std::shared_ptr<std::vector<FieldTransform>>)fieldTransforms
  180. fieldMask:(std::shared_ptr<std::vector<FieldPath>>)fieldMask
  181. NS_DESIGNATED_INITIALIZER;
  182. // Helpers to get a FSTParseContext for a child field.
  183. - (instancetype)contextForField:(NSString *)fieldName;
  184. - (instancetype)contextForFieldPath:(const FieldPath &)fieldPath;
  185. - (instancetype)contextForArrayIndex:(NSUInteger)index;
  186. /** Returns true for the non-query parse contexts (Set, MergeSet and Update) */
  187. - (BOOL)isWrite;
  188. - (const FieldPath *)path;
  189. - (const std::vector<FieldPath> *)fieldMask;
  190. - (void)appendToFieldMaskWithFieldPath:(FieldPath)fieldPath;
  191. - (const std::vector<FieldTransform> *)fieldTransforms;
  192. - (void)appendToFieldTransformsWithFieldPath:(FieldPath)fieldPath
  193. transformOperation:
  194. (std::unique_ptr<TransformOperation>)transformOperation;
  195. @end
  196. @implementation FSTParseContext {
  197. /** The current path being parsed. */
  198. // TODO(b/34871131): path should never be nullptr, but we don't support array paths right now.
  199. std::unique_ptr<FieldPath> _path;
  200. // _fieldMask and _fieldTransforms are shared across all active context objects to accumulate the
  201. // result. For example, the result of calling any of contextForField, contextForFieldPath and
  202. // contextForArrayIndex shares the ownership of _fieldMask and _fieldTransforms.
  203. std::shared_ptr<std::vector<FieldPath>> _fieldMask;
  204. std::shared_ptr<std::vector<FieldTransform>> _fieldTransforms;
  205. }
  206. + (instancetype)contextWithSource:(FSTUserDataSource)dataSource
  207. path:(std::unique_ptr<FieldPath>)path {
  208. FSTParseContext *context =
  209. [[FSTParseContext alloc] initWithSource:dataSource
  210. path:std::move(path)
  211. arrayElement:NO
  212. fieldTransforms:std::make_shared<std::vector<FieldTransform>>()
  213. fieldMask:std::make_shared<std::vector<FieldPath>>()];
  214. [context validatePath];
  215. return context;
  216. }
  217. - (instancetype)initWithSource:(FSTUserDataSource)dataSource
  218. path:(std::unique_ptr<FieldPath>)path
  219. arrayElement:(BOOL)arrayElement
  220. fieldTransforms:(std::shared_ptr<std::vector<FieldTransform>>)fieldTransforms
  221. fieldMask:(std::shared_ptr<std::vector<FieldPath>>)fieldMask {
  222. if (self = [super init]) {
  223. _dataSource = dataSource;
  224. _path = std::move(path);
  225. _arrayElement = arrayElement;
  226. _fieldTransforms = std::move(fieldTransforms);
  227. _fieldMask = std::move(fieldMask);
  228. }
  229. return self;
  230. }
  231. - (instancetype)contextForField:(NSString *)fieldName {
  232. std::unique_ptr<FieldPath> path{};
  233. if (_path) {
  234. path = absl::make_unique<FieldPath>(_path->Append(util::MakeString(fieldName)));
  235. }
  236. FSTParseContext *context = [[FSTParseContext alloc] initWithSource:self.dataSource
  237. path:std::move(path)
  238. arrayElement:NO
  239. fieldTransforms:_fieldTransforms
  240. fieldMask:_fieldMask];
  241. [context validatePathSegment:fieldName];
  242. return context;
  243. }
  244. - (instancetype)contextForFieldPath:(const FieldPath &)fieldPath {
  245. std::unique_ptr<FieldPath> path{};
  246. if (_path) {
  247. path = absl::make_unique<FieldPath>(_path->Append(fieldPath));
  248. }
  249. FSTParseContext *context = [[FSTParseContext alloc] initWithSource:self.dataSource
  250. path:std::move(path)
  251. arrayElement:NO
  252. fieldTransforms:_fieldTransforms
  253. fieldMask:_fieldMask];
  254. [context validatePath];
  255. return context;
  256. }
  257. - (instancetype)contextForArrayIndex:(NSUInteger)index {
  258. // TODO(b/34871131): We don't support array paths right now; so make path nil.
  259. return [[FSTParseContext alloc] initWithSource:self.dataSource
  260. path:nil
  261. arrayElement:YES
  262. fieldTransforms:_fieldTransforms
  263. fieldMask:_fieldMask];
  264. }
  265. /**
  266. * Returns a string that can be appended to error messages indicating what field caused the error.
  267. */
  268. - (NSString *)fieldDescription {
  269. // TODO(b/34871131): Remove nil check once we have proper paths for fields within arrays.
  270. if (!_path || _path->empty()) {
  271. return @"";
  272. } else {
  273. return [NSString stringWithFormat:@" (found in field %s)", _path->CanonicalString().c_str()];
  274. }
  275. }
  276. - (BOOL)isWrite {
  277. switch (self.dataSource) {
  278. case FSTUserDataSourceSet: // Falls through.
  279. case FSTUserDataSourceMergeSet: // Falls through.
  280. case FSTUserDataSourceUpdate:
  281. return YES;
  282. case FSTUserDataSourceArgument:
  283. return NO;
  284. default:
  285. FSTThrowInvalidArgument(@"Unexpected case for FSTUserDataSource: %d", self.dataSource);
  286. }
  287. }
  288. - (void)validatePath {
  289. // TODO(b/34871131): Remove nil check once we have proper paths for fields within arrays.
  290. if (_path == nullptr) {
  291. return;
  292. }
  293. for (const auto &segment : *_path) {
  294. [self validatePathSegment:util::WrapNSStringNoCopy(segment)];
  295. }
  296. }
  297. - (void)validatePathSegment:(NSString *)segment {
  298. if ([self isWrite] && [segment hasPrefix:RESERVED_FIELD_DESIGNATOR] &&
  299. [segment hasSuffix:RESERVED_FIELD_DESIGNATOR]) {
  300. FSTThrowInvalidArgument(@"Document fields cannot begin and end with %@%@",
  301. RESERVED_FIELD_DESIGNATOR, [self fieldDescription]);
  302. }
  303. }
  304. - (const FieldPath *)path {
  305. return _path.get();
  306. }
  307. - (const std::vector<FieldPath> *)fieldMask {
  308. return _fieldMask.get();
  309. }
  310. - (void)appendToFieldMaskWithFieldPath:(FieldPath)fieldPath {
  311. _fieldMask->push_back(std::move(fieldPath));
  312. }
  313. - (const std::vector<FieldTransform> *)fieldTransforms {
  314. return _fieldTransforms.get();
  315. }
  316. - (void)appendToFieldTransformsWithFieldPath:(FieldPath)fieldPath
  317. transformOperation:
  318. (std::unique_ptr<TransformOperation>)transformOperation {
  319. _fieldTransforms->emplace_back(std::move(fieldPath), std::move(transformOperation));
  320. }
  321. @end
  322. #pragma mark - FSTDocumentKeyReference
  323. @implementation FSTDocumentKeyReference {
  324. DocumentKey _key;
  325. }
  326. - (instancetype)initWithKey:(DocumentKey)key databaseID:(const DatabaseId *)databaseID {
  327. self = [super init];
  328. if (self) {
  329. _key = std::move(key);
  330. _databaseID = databaseID;
  331. }
  332. return self;
  333. }
  334. - (const firebase::firestore::model::DocumentKey &)key {
  335. return _key;
  336. }
  337. @end
  338. #pragma mark - FSTUserDataConverter
  339. @interface FSTUserDataConverter ()
  340. // Does not own the DatabaseId instance.
  341. @property(assign, nonatomic, readonly) const DatabaseId *databaseID;
  342. @property(strong, nonatomic, readonly) FSTPreConverterBlock preConverter;
  343. @end
  344. @implementation FSTUserDataConverter
  345. - (instancetype)initWithDatabaseID:(const DatabaseId *)databaseID
  346. preConverter:(FSTPreConverterBlock)preConverter {
  347. self = [super init];
  348. if (self) {
  349. _databaseID = databaseID;
  350. _preConverter = preConverter;
  351. }
  352. return self;
  353. }
  354. - (FSTParsedSetData *)parsedMergeData:(id)input {
  355. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  356. // Obj-C to verify the type for us.
  357. if (![input isKindOfClass:[NSDictionary class]]) {
  358. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  359. }
  360. FSTParseContext *context =
  361. [FSTParseContext contextWithSource:FSTUserDataSourceMergeSet
  362. path:absl::make_unique<FieldPath>(FieldPath::EmptyPath())];
  363. FSTObjectValue *updateData = (FSTObjectValue *)[self parseData:input context:context];
  364. return [[FSTParsedSetData alloc] initWithData:updateData
  365. fieldMask:FieldMask{*context.fieldMask}
  366. fieldTransforms:*context.fieldTransforms];
  367. }
  368. - (FSTParsedSetData *)parsedSetData:(id)input {
  369. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  370. // Obj-C to verify the type for us.
  371. if (![input isKindOfClass:[NSDictionary class]]) {
  372. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  373. }
  374. FSTParseContext *context =
  375. [FSTParseContext contextWithSource:FSTUserDataSourceSet
  376. path:absl::make_unique<FieldPath>(FieldPath::EmptyPath())];
  377. FSTObjectValue *updateData = (FSTObjectValue *)[self parseData:input context:context];
  378. return
  379. [[FSTParsedSetData alloc] initWithData:updateData fieldTransforms:*context.fieldTransforms];
  380. }
  381. - (FSTParsedUpdateData *)parsedUpdateData:(id)input {
  382. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  383. // Obj-C to verify the type for us.
  384. if (![input isKindOfClass:[NSDictionary class]]) {
  385. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  386. }
  387. NSDictionary *dict = input;
  388. __block std::vector<FieldPath> fieldMaskPaths{};
  389. __block FSTObjectValue *updateData = [FSTObjectValue objectValue];
  390. FSTParseContext *context =
  391. [FSTParseContext contextWithSource:FSTUserDataSourceUpdate
  392. path:absl::make_unique<FieldPath>(FieldPath::EmptyPath())];
  393. [dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
  394. FieldPath path{};
  395. if ([key isKindOfClass:[NSString class]]) {
  396. path = [FIRFieldPath pathWithDotSeparatedString:key].internalValue;
  397. } else if ([key isKindOfClass:[FIRFieldPath class]]) {
  398. path = ((FIRFieldPath *)key).internalValue;
  399. } else {
  400. FSTThrowInvalidArgument(
  401. @"Dictionary keys in updateData: must be NSStrings or FIRFieldPaths.");
  402. }
  403. value = self.preConverter(value);
  404. if ([value isKindOfClass:[FSTDeleteFieldValue class]]) {
  405. // Add it to the field mask, but don't add anything to updateData.
  406. fieldMaskPaths.push_back(path);
  407. } else {
  408. FSTFieldValue *_Nullable parsedValue =
  409. [self parseData:value context:[context contextForFieldPath:path]];
  410. if (parsedValue) {
  411. fieldMaskPaths.push_back(path);
  412. updateData = [updateData objectBySettingValue:parsedValue forPath:path];
  413. }
  414. }
  415. }];
  416. return [[FSTParsedUpdateData alloc] initWithData:updateData
  417. fieldMask:FieldMask{fieldMaskPaths}
  418. fieldTransforms:*context.fieldTransforms];
  419. }
  420. - (FSTFieldValue *)parsedQueryValue:(id)input {
  421. FSTParseContext *context =
  422. [FSTParseContext contextWithSource:FSTUserDataSourceArgument
  423. path:absl::make_unique<FieldPath>(FieldPath::EmptyPath())];
  424. FSTFieldValue *_Nullable parsed = [self parseData:input context:context];
  425. FSTAssert(parsed, @"Parsed data should not be nil.");
  426. FSTAssert(context.fieldTransforms->empty(), @"Field transforms should have been disallowed.");
  427. return parsed;
  428. }
  429. /**
  430. * Internal helper for parsing user data.
  431. *
  432. * @param input Data to be parsed.
  433. * @param context A context object representing the current path being parsed, the source of the
  434. * data being parsed, etc.
  435. *
  436. * @return The parsed value, or nil if the value was a FieldValue sentinel that should not be
  437. * included in the resulting parsed data.
  438. */
  439. - (nullable FSTFieldValue *)parseData:(id)input context:(FSTParseContext *)context {
  440. input = self.preConverter(input);
  441. if ([input isKindOfClass:[NSDictionary class]]) {
  442. return [self parseDictionary:(NSDictionary *)input context:context];
  443. } else if ([input isKindOfClass:[FIRFieldValue class]]) {
  444. // FieldValues usually parse into transforms (except FieldValue.delete()) in which case we
  445. // do not want to include this field in our parsed data (as doing so will overwrite the field
  446. // directly prior to the transform trying to transform it). So we don't call appendToFieldMask
  447. // and we return nil as our parsing result.
  448. [self parseSentinelFieldValue:(FIRFieldValue *)input context:context];
  449. return nil;
  450. } else {
  451. // If context.path is nil we are already inside an array and we don't support field mask paths
  452. // more granular than the top-level array.
  453. if (context.path) {
  454. [context appendToFieldMaskWithFieldPath:*context.path];
  455. }
  456. if ([input isKindOfClass:[NSArray class]]) {
  457. // TODO(b/34871131): Include the path containing the array in the error message.
  458. if (context.isArrayElement) {
  459. FSTThrowInvalidArgument(@"Nested arrays are not supported");
  460. }
  461. return [self parseArray:(NSArray *)input context:context];
  462. } else {
  463. return [self parseScalarValue:input context:context];
  464. }
  465. }
  466. }
  467. - (FSTFieldValue *)parseDictionary:(NSDictionary *)dict context:(FSTParseContext *)context {
  468. NSMutableDictionary<NSString *, FSTFieldValue *> *result =
  469. [NSMutableDictionary dictionaryWithCapacity:dict.count];
  470. [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
  471. FSTFieldValue *_Nullable parsedValue =
  472. [self parseData:value context:[context contextForField:key]];
  473. if (parsedValue) {
  474. result[key] = parsedValue;
  475. }
  476. }];
  477. return [[FSTObjectValue alloc] initWithDictionary:result];
  478. }
  479. - (FSTFieldValue *)parseArray:(NSArray *)array context:(FSTParseContext *)context {
  480. NSMutableArray<FSTFieldValue *> *result = [NSMutableArray arrayWithCapacity:array.count];
  481. [array enumerateObjectsUsingBlock:^(id entry, NSUInteger idx, BOOL *stop) {
  482. FSTFieldValue *_Nullable parsedEntry =
  483. [self parseData:entry context:[context contextForArrayIndex:idx]];
  484. if (!parsedEntry) {
  485. // Just include nulls in the array for fields being replaced with a sentinel.
  486. parsedEntry = [FSTNullValue nullValue];
  487. }
  488. [result addObject:parsedEntry];
  489. }];
  490. return [[FSTArrayValue alloc] initWithValueNoCopy:result];
  491. }
  492. /**
  493. * "Parses" the provided FIRFieldValue, adding any necessary transforms to
  494. * context.fieldTransforms.
  495. */
  496. - (void)parseSentinelFieldValue:(FIRFieldValue *)fieldValue context:(FSTParseContext *)context {
  497. // Sentinels are only supported with writes, and not within arrays.
  498. if (![context isWrite]) {
  499. FSTThrowInvalidArgument(@"%@ can only be used with updateData() and setData()%@",
  500. fieldValue.methodName, [context fieldDescription]);
  501. }
  502. if (!context.path) {
  503. FSTThrowInvalidArgument(@"%@ is not currently supported inside arrays", fieldValue.methodName);
  504. }
  505. if ([fieldValue isKindOfClass:[FSTDeleteFieldValue class]]) {
  506. if (context.dataSource == FSTUserDataSourceMergeSet) {
  507. // No transform to add for a delete, but we need to add it to our fieldMask so it gets
  508. // deleted.
  509. [context appendToFieldMaskWithFieldPath:*context.path];
  510. } else if (context.dataSource == FSTUserDataSourceUpdate) {
  511. FSTAssert(context.path->size() > 0,
  512. @"FieldValue.delete() at the top level should have already been handled.");
  513. FSTThrowInvalidArgument(
  514. @"FieldValue.delete() can only appear at the top level of your "
  515. "update data%@",
  516. [context fieldDescription]);
  517. } else {
  518. // We shouldn't encounter delete sentinels for queries or non-merge setData calls.
  519. FSTThrowInvalidArgument(
  520. @"FieldValue.delete() can only be used with updateData() and setData() with "
  521. @"merge:true%@",
  522. [context fieldDescription]);
  523. }
  524. } else if ([fieldValue isKindOfClass:[FSTServerTimestampFieldValue class]]) {
  525. [context appendToFieldTransformsWithFieldPath:*context.path
  526. transformOperation:absl::make_unique<ServerTimestampTransform>(
  527. ServerTimestampTransform::Get())];
  528. } else if ([fieldValue isKindOfClass:[FSTArrayUnionFieldValue class]]) {
  529. std::vector<FSTFieldValue *> parsedElements =
  530. [self parseArrayTransformElements:((FSTArrayUnionFieldValue *)fieldValue).elements];
  531. auto array_union = absl::make_unique<ArrayTransform>(TransformOperation::Type::ArrayUnion,
  532. std::move(parsedElements));
  533. [context appendToFieldTransformsWithFieldPath:*context.path
  534. transformOperation:std::move(array_union)];
  535. } else if ([fieldValue isKindOfClass:[FSTArrayRemoveFieldValue class]]) {
  536. std::vector<FSTFieldValue *> parsedElements =
  537. [self parseArrayTransformElements:((FSTArrayRemoveFieldValue *)fieldValue).elements];
  538. auto array_remove = absl::make_unique<ArrayTransform>(TransformOperation::Type::ArrayRemove,
  539. std::move(parsedElements));
  540. [context appendToFieldTransformsWithFieldPath:*context.path
  541. transformOperation:std::move(array_remove)];
  542. } else {
  543. FSTFail(@"Unknown FIRFieldValue type: %@", NSStringFromClass([fieldValue class]));
  544. }
  545. }
  546. /**
  547. * Helper to parse a scalar value (i.e. not an NSDictionary, NSArray, or FIRFieldValue).
  548. *
  549. * Note that it handles all NSNumber values that are encodable as int64_t or doubles
  550. * (depending on the underlying type of the NSNumber). Unsigned integer values are handled though
  551. * any value outside what is representable by int64_t (a signed 64-bit value) will throw an
  552. * exception.
  553. *
  554. * @return The parsed value.
  555. */
  556. - (FSTFieldValue *)parseScalarValue:(nullable id)input context:(FSTParseContext *)context {
  557. if (!input || [input isMemberOfClass:[NSNull class]]) {
  558. return [FSTNullValue nullValue];
  559. } else if ([input isKindOfClass:[NSNumber class]]) {
  560. // Recover the underlying type of the number, using the method described here:
  561. // http://stackoverflow.com/questions/2518761/get-type-of-nsnumber
  562. const char *cType = [input objCType];
  563. // Type Encoding values taken from
  564. // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/
  565. // Articles/ocrtTypeEncodings.html
  566. switch (cType[0]) {
  567. case 'q':
  568. return [FSTIntegerValue integerValue:[input longLongValue]];
  569. case 'i': // Falls through.
  570. case 's': // Falls through.
  571. case 'l': // Falls through.
  572. case 'I': // Falls through.
  573. case 'S':
  574. // Coerce integer values that aren't long long. Allow unsigned integer types that are
  575. // guaranteed small enough to skip a length check.
  576. return [FSTIntegerValue integerValue:[input longLongValue]];
  577. case 'L': // Falls through.
  578. case 'Q':
  579. // Unsigned integers that could be too large. Note that the 'L' (long) case is handled here
  580. // because when compiled for LP64, unsigned long is 64 bits and could overflow int64_t.
  581. {
  582. unsigned long long extended = [input unsignedLongLongValue];
  583. if (extended > LLONG_MAX) {
  584. FSTThrowInvalidArgument(@"NSNumber (%llu) is too large%@",
  585. [input unsignedLongLongValue], [context fieldDescription]);
  586. } else {
  587. return [FSTIntegerValue integerValue:(int64_t)extended];
  588. }
  589. }
  590. case 'f':
  591. return [FSTDoubleValue doubleValue:[input doubleValue]];
  592. case 'd':
  593. // Double values are already the right type, so just reuse the existing boxed double.
  594. //
  595. // Note that NSNumber already performs NaN normalization to a single shared instance
  596. // so there's no need to treat NaN specially here.
  597. return [FSTDoubleValue doubleValue:[input doubleValue]];
  598. case 'B': // Falls through.
  599. case 'c': // Falls through.
  600. case 'C':
  601. // Boolean values are weird.
  602. //
  603. // On arm64, objCType of a BOOL-valued NSNumber will be "c", even though @encode(BOOL)
  604. // returns "B". "c" is the same as @encode(signed char). Unfortunately this means that
  605. // legitimate usage of signed chars is impossible, but this should be rare.
  606. //
  607. // Additionally, for consistency, map unsigned chars to bools in the same way.
  608. return [FSTBooleanValue booleanValue:[input boolValue]];
  609. default:
  610. // All documented codes should be handled above, so this shouldn't happen.
  611. FSTCFail(@"Unknown NSNumber objCType %s on %@", cType, input);
  612. }
  613. } else if ([input isKindOfClass:[NSString class]]) {
  614. return [FSTStringValue stringValue:input];
  615. } else if ([input isKindOfClass:[NSDate class]]) {
  616. return [FSTTimestampValue timestampValue:[FIRTimestamp timestampWithDate:input]];
  617. } else if ([input isKindOfClass:[FIRTimestamp class]]) {
  618. FIRTimestamp *originalTimestamp = (FIRTimestamp *)input;
  619. FIRTimestamp *truncatedTimestamp =
  620. [FIRTimestamp timestampWithSeconds:originalTimestamp.seconds
  621. nanoseconds:originalTimestamp.nanoseconds / 1000 * 1000];
  622. return [FSTTimestampValue timestampValue:truncatedTimestamp];
  623. } else if ([input isKindOfClass:[FIRGeoPoint class]]) {
  624. return [FSTGeoPointValue geoPointValue:input];
  625. } else if ([input isKindOfClass:[NSData class]]) {
  626. return [FSTBlobValue blobValue:input];
  627. } else if ([input isKindOfClass:[FSTDocumentKeyReference class]]) {
  628. FSTDocumentKeyReference *reference = input;
  629. if (*reference.databaseID != *self.databaseID) {
  630. const DatabaseId *other = reference.databaseID;
  631. FSTThrowInvalidArgument(
  632. @"Document Reference is for database %s/%s but should be for database %s/%s%@",
  633. other->project_id().c_str(), other->database_id().c_str(),
  634. self.databaseID->project_id().c_str(), self.databaseID->database_id().c_str(),
  635. [context fieldDescription]);
  636. }
  637. return [FSTReferenceValue referenceValue:reference.key databaseID:self.databaseID];
  638. } else if ([input isKindOfClass:[FIRFieldValue class]]) {
  639. if ([input isKindOfClass:[FSTDeleteFieldValue class]]) {
  640. if (context.dataSource == FSTUserDataSourceMergeSet) {
  641. return nil;
  642. } else if (context.dataSource == FSTUserDataSourceUpdate) {
  643. FSTAssert(context.path->size() > 0,
  644. @"FieldValue.delete() at the top level should have already been handled.");
  645. FSTThrowInvalidArgument(
  646. @"FieldValue.delete() can only appear at the top level of your update data%@",
  647. [context fieldDescription]);
  648. } else {
  649. // We shouldn't encounter delete sentinels for queries or non-merge setData calls.
  650. FSTThrowInvalidArgument(
  651. @"FieldValue.delete() can only be used with updateData() and setData() with "
  652. @"merge: true.");
  653. }
  654. } else if ([input isKindOfClass:[FSTServerTimestampFieldValue class]]) {
  655. if (![context isWrite]) {
  656. FSTThrowInvalidArgument(
  657. @"FieldValue.serverTimestamp() can only be used with setData() and updateData().");
  658. }
  659. if (!context.path) {
  660. FSTThrowInvalidArgument(
  661. @"FieldValue.serverTimestamp() is not currently supported inside arrays%@",
  662. [context fieldDescription]);
  663. }
  664. [context appendToFieldTransformsWithFieldPath:*context.path
  665. transformOperation:absl::make_unique<ServerTimestampTransform>(
  666. ServerTimestampTransform::Get())];
  667. // Return nil so this value is omitted from the parsed result.
  668. return nil;
  669. } else {
  670. FSTFail(@"Unknown FIRFieldValue type: %@", NSStringFromClass([input class]));
  671. }
  672. } else {
  673. FSTThrowInvalidArgument(@"Unsupported type: %@%@", NSStringFromClass([input class]),
  674. [context fieldDescription]);
  675. }
  676. }
  677. - (std::vector<FSTFieldValue *>)parseArrayTransformElements:(NSArray<id> *)elements {
  678. std::vector<FSTFieldValue *> results;
  679. for (NSUInteger i = 0; i < elements.count; i++) {
  680. id element = elements[i];
  681. // Although array transforms are used with writes, the actual elements being unioned or removed
  682. // are not considered writes since they cannot contain any FieldValue sentinels, etc.
  683. FSTParseContext *context =
  684. [FSTParseContext contextWithSource:FSTUserDataSourceArgument
  685. path:absl::make_unique<FieldPath>(FieldPath::EmptyPath())];
  686. FSTFieldValue *parsedElement =
  687. [self parseData:element context:[context contextForArrayIndex:i]];
  688. FSTAssert(parsedElement && context.fieldTransforms->size() == 0,
  689. @"Failed to properly parse array transform element: %@", element);
  690. results.push_back(parsedElement);
  691. }
  692. return results;
  693. }
  694. @end
  695. NS_ASSUME_NONNULL_END