FSTUserDataConverter.mm 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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. #import "FIRTimestamp.h"
  18. #import "FIRGeoPoint.h"
  19. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  20. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  21. #import "Firestore/Source/API/FIRFieldValue+Internal.h"
  22. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  23. #import "Firestore/Source/API/FIRSetOptions+Internal.h"
  24. #import "Firestore/Source/Model/FSTDocumentKey.h"
  25. #import "Firestore/Source/Model/FSTFieldValue.h"
  26. #import "Firestore/Source/Model/FSTMutation.h"
  27. #import "Firestore/Source/Model/FSTPath.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/util/string_apple.h"
  32. namespace util = firebase::firestore::util;
  33. using firebase::firestore::model::DatabaseId;
  34. NS_ASSUME_NONNULL_BEGIN
  35. static NSString *const RESERVED_FIELD_DESIGNATOR = @"__";
  36. #pragma mark - FSTParsedSetData
  37. @implementation FSTParsedSetData
  38. - (instancetype)initWithData:(FSTObjectValue *)data
  39. fieldMask:(nullable FSTFieldMask *)fieldMask
  40. fieldTransforms:(NSArray<FSTFieldTransform *> *)fieldTransforms {
  41. self = [super init];
  42. if (self) {
  43. _data = data;
  44. _fieldMask = fieldMask;
  45. _fieldTransforms = fieldTransforms;
  46. }
  47. return self;
  48. }
  49. - (NSArray<FSTMutation *> *)mutationsWithKey:(FSTDocumentKey *)key
  50. precondition:(FSTPrecondition *)precondition {
  51. NSMutableArray<FSTMutation *> *mutations = [NSMutableArray array];
  52. if (self.fieldMask) {
  53. [mutations addObject:[[FSTPatchMutation alloc] initWithKey:key
  54. fieldMask:self.fieldMask
  55. value:self.data
  56. precondition:precondition]];
  57. } else {
  58. [mutations addObject:[[FSTSetMutation alloc] initWithKey:key
  59. value:self.data
  60. precondition:precondition]];
  61. }
  62. if (self.fieldTransforms.count > 0) {
  63. [mutations addObject:[[FSTTransformMutation alloc] initWithKey:key
  64. fieldTransforms:self.fieldTransforms]];
  65. }
  66. return mutations;
  67. }
  68. @end
  69. #pragma mark - FSTParsedUpdateData
  70. @implementation FSTParsedUpdateData
  71. - (instancetype)initWithData:(FSTObjectValue *)data
  72. fieldMask:(FSTFieldMask *)fieldMask
  73. fieldTransforms:(NSArray<FSTFieldTransform *> *)fieldTransforms {
  74. self = [super init];
  75. if (self) {
  76. _data = data;
  77. _fieldMask = fieldMask;
  78. _fieldTransforms = fieldTransforms;
  79. }
  80. return self;
  81. }
  82. - (NSArray<FSTMutation *> *)mutationsWithKey:(FSTDocumentKey *)key
  83. precondition:(FSTPrecondition *)precondition {
  84. NSMutableArray<FSTMutation *> *mutations = [NSMutableArray array];
  85. [mutations addObject:[[FSTPatchMutation alloc] initWithKey:key
  86. fieldMask:self.fieldMask
  87. value:self.data
  88. precondition:precondition]];
  89. if (self.fieldTransforms.count > 0) {
  90. [mutations addObject:[[FSTTransformMutation alloc] initWithKey:key
  91. fieldTransforms:self.fieldTransforms]];
  92. }
  93. return mutations;
  94. }
  95. @end
  96. /**
  97. * Represents what type of API method provided the data being parsed; useful for determining which
  98. * error conditions apply during parsing and providing better error messages.
  99. */
  100. typedef NS_ENUM(NSInteger, FSTUserDataSource) {
  101. FSTUserDataSourceSet,
  102. FSTUserDataSourceMergeSet,
  103. FSTUserDataSourceUpdate,
  104. FSTUserDataSourceQueryValue, // from a where clause or cursor bound.
  105. };
  106. #pragma mark - FSTParseContext
  107. /**
  108. * A "context" object passed around while parsing user data.
  109. */
  110. @interface FSTParseContext : NSObject
  111. /** The current path being parsed. */
  112. // TODO(b/34871131): path should never be nil, but we don't support array paths right now.
  113. @property(nonatomic, strong, readonly, nullable) FSTFieldPath *path;
  114. /** Whether or not this context corresponds to an element of an array. */
  115. @property(nonatomic, assign, readonly, getter=isArrayElement) BOOL arrayElement;
  116. /**
  117. * What type of API method provided the data being parsed; useful for determining which error
  118. * conditions apply during parsing and providing better error messages.
  119. */
  120. @property(nonatomic, assign) FSTUserDataSource dataSource;
  121. @property(nonatomic, strong, readonly) NSMutableArray<FSTFieldTransform *> *fieldTransforms;
  122. @property(nonatomic, strong, readonly) NSMutableArray<FSTFieldPath *> *fieldMask;
  123. - (instancetype)init NS_UNAVAILABLE;
  124. /**
  125. * Initializes a FSTParseContext with the given source and path.
  126. *
  127. * @param dataSource Indicates what kind of API method this data came from.
  128. * @param path A path within the object being parsed. This could be an empty path (in which case
  129. * the context represents the root of the data being parsed), or a nonempty path (indicating the
  130. * context represents a nested location within the data).
  131. *
  132. * TODO(b/34871131): We don't support array paths right now, so path can be nil to indicate
  133. * the context represents any location within an array (in which case certain features will not work
  134. * and errors will be somewhat compromised).
  135. */
  136. - (instancetype)initWithSource:(FSTUserDataSource)dataSource
  137. path:(nullable FSTFieldPath *)path
  138. arrayElement:(BOOL)arrayElement
  139. fieldTransforms:(NSMutableArray<FSTFieldTransform *> *)fieldTransforms
  140. fieldMask:(NSMutableArray<FSTFieldPath *> *)fieldMask
  141. NS_DESIGNATED_INITIALIZER;
  142. // Helpers to get a FSTParseContext for a child field.
  143. - (instancetype)contextForField:(NSString *)fieldName;
  144. - (instancetype)contextForFieldPath:(FSTFieldPath *)fieldPath;
  145. - (instancetype)contextForArrayIndex:(NSUInteger)index;
  146. /** Returns true for the non-query parse contexts (Set, MergeSet and Update) */
  147. - (BOOL)isWrite;
  148. @end
  149. @implementation FSTParseContext
  150. + (instancetype)contextWithSource:(FSTUserDataSource)dataSource path:(nullable FSTFieldPath *)path {
  151. FSTParseContext *context = [[FSTParseContext alloc] initWithSource:dataSource
  152. path:path
  153. arrayElement:NO
  154. fieldTransforms:[NSMutableArray array]
  155. fieldMask:[NSMutableArray array]];
  156. [context validatePath];
  157. return context;
  158. }
  159. - (instancetype)initWithSource:(FSTUserDataSource)dataSource
  160. path:(nullable FSTFieldPath *)path
  161. arrayElement:(BOOL)arrayElement
  162. fieldTransforms:(NSMutableArray<FSTFieldTransform *> *)fieldTransforms
  163. fieldMask:(NSMutableArray<FSTFieldPath *> *)fieldMask {
  164. if (self = [super init]) {
  165. _dataSource = dataSource;
  166. _path = path;
  167. _arrayElement = arrayElement;
  168. _fieldTransforms = fieldTransforms;
  169. _fieldMask = fieldMask;
  170. }
  171. return self;
  172. }
  173. - (instancetype)contextForField:(NSString *)fieldName {
  174. FSTParseContext *context =
  175. [[FSTParseContext alloc] initWithSource:self.dataSource
  176. path:[self.path pathByAppendingSegment:fieldName]
  177. arrayElement:NO
  178. fieldTransforms:self.fieldTransforms
  179. fieldMask:self.fieldMask];
  180. [context validatePathSegment:fieldName];
  181. return context;
  182. }
  183. - (instancetype)contextForFieldPath:(FSTFieldPath *)fieldPath {
  184. FSTParseContext *context =
  185. [[FSTParseContext alloc] initWithSource:self.dataSource
  186. path:[self.path pathByAppendingPath:fieldPath]
  187. arrayElement:NO
  188. fieldTransforms:self.fieldTransforms
  189. fieldMask:self.fieldMask];
  190. [context validatePath];
  191. return context;
  192. }
  193. - (instancetype)contextForArrayIndex:(NSUInteger)index {
  194. // TODO(b/34871131): We don't support array paths right now; so make path nil.
  195. return [[FSTParseContext alloc] initWithSource:self.dataSource
  196. path:nil
  197. arrayElement:YES
  198. fieldTransforms:self.fieldTransforms
  199. fieldMask:self.fieldMask];
  200. }
  201. /**
  202. * Returns a string that can be appended to error messages indicating what field caused the error.
  203. */
  204. - (NSString *)fieldDescription {
  205. // TODO(b/34871131): Remove nil check once we have proper paths for fields within arrays.
  206. if (!self.path || self.path.empty) {
  207. return @"";
  208. } else {
  209. return [NSString stringWithFormat:@" (found in field %@)", self.path];
  210. }
  211. }
  212. - (BOOL)isWrite {
  213. switch (self.dataSource) {
  214. case FSTUserDataSourceSet: // Falls through.
  215. case FSTUserDataSourceMergeSet: // Falls through.
  216. case FSTUserDataSourceUpdate:
  217. return YES;
  218. case FSTUserDataSourceQueryValue:
  219. return NO;
  220. default:
  221. FSTThrowInvalidArgument(@"Unexpected case for FSTUserDataSource: %d", self.dataSource);
  222. }
  223. }
  224. - (void)validatePath {
  225. // TODO(b/34871131): Remove nil check once we have proper paths for fields within arrays.
  226. if (self.path == nil) {
  227. return;
  228. }
  229. for (int i = 0; i < self.path.length; i++) {
  230. [self validatePathSegment:[self.path segmentAtIndex:i]];
  231. }
  232. }
  233. - (void)validatePathSegment:(NSString *)segment {
  234. if ([self isWrite] && [segment hasPrefix:RESERVED_FIELD_DESIGNATOR] &&
  235. [segment hasSuffix:RESERVED_FIELD_DESIGNATOR]) {
  236. FSTThrowInvalidArgument(@"Document fields cannot begin and end with %@%@",
  237. RESERVED_FIELD_DESIGNATOR, [self fieldDescription]);
  238. }
  239. }
  240. @end
  241. #pragma mark - FSTDocumentKeyReference
  242. @implementation FSTDocumentKeyReference
  243. - (instancetype)initWithKey:(FSTDocumentKey *)key databaseID:(const DatabaseId *)databaseID {
  244. self = [super init];
  245. if (self) {
  246. _key = key;
  247. _databaseID = databaseID;
  248. }
  249. return self;
  250. }
  251. @end
  252. #pragma mark - FSTUserDataConverter
  253. @interface FSTUserDataConverter ()
  254. // Does not own the DatabaseId instance.
  255. @property(assign, nonatomic, readonly) const DatabaseId *databaseID;
  256. @property(strong, nonatomic, readonly) FSTPreConverterBlock preConverter;
  257. @end
  258. @implementation FSTUserDataConverter
  259. - (instancetype)initWithDatabaseID:(const DatabaseId *)databaseID
  260. preConverter:(FSTPreConverterBlock)preConverter {
  261. self = [super init];
  262. if (self) {
  263. _databaseID = databaseID;
  264. _preConverter = preConverter;
  265. }
  266. return self;
  267. }
  268. - (FSTParsedSetData *)parsedMergeData:(id)input {
  269. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  270. // Obj-C to verify the type for us.
  271. if (![input isKindOfClass:[NSDictionary class]]) {
  272. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  273. }
  274. FSTParseContext *context =
  275. [FSTParseContext contextWithSource:FSTUserDataSourceMergeSet path:[FSTFieldPath emptyPath]];
  276. FSTObjectValue *updateData = (FSTObjectValue *)[self parseData:input context:context];
  277. return
  278. [[FSTParsedSetData alloc] initWithData:updateData
  279. fieldMask:[[FSTFieldMask alloc] initWithFields:context.fieldMask]
  280. fieldTransforms:context.fieldTransforms];
  281. }
  282. - (FSTParsedSetData *)parsedSetData:(id)input {
  283. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  284. // Obj-C to verify the type for us.
  285. if (![input isKindOfClass:[NSDictionary class]]) {
  286. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  287. }
  288. FSTParseContext *context =
  289. [FSTParseContext contextWithSource:FSTUserDataSourceSet path:[FSTFieldPath emptyPath]];
  290. FSTObjectValue *updateData = (FSTObjectValue *)[self parseData:input context:context];
  291. return [[FSTParsedSetData alloc] initWithData:updateData
  292. fieldMask:nil
  293. fieldTransforms:context.fieldTransforms];
  294. }
  295. - (FSTParsedUpdateData *)parsedUpdateData:(id)input {
  296. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  297. // Obj-C to verify the type for us.
  298. if (![input isKindOfClass:[NSDictionary class]]) {
  299. FSTThrowInvalidArgument(@"Data to be written must be an NSDictionary.");
  300. }
  301. NSDictionary *dict = input;
  302. NSMutableArray<FSTFieldPath *> *fieldMaskPaths = [NSMutableArray array];
  303. __block FSTObjectValue *updateData = [FSTObjectValue objectValue];
  304. FSTParseContext *context =
  305. [FSTParseContext contextWithSource:FSTUserDataSourceUpdate path:[FSTFieldPath emptyPath]];
  306. [dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *stop) {
  307. FSTFieldPath *path;
  308. if ([key isKindOfClass:[NSString class]]) {
  309. path = [FIRFieldPath pathWithDotSeparatedString:key].internalValue;
  310. } else if ([key isKindOfClass:[FIRFieldPath class]]) {
  311. path = ((FIRFieldPath *)key).internalValue;
  312. } else {
  313. FSTThrowInvalidArgument(
  314. @"Dictionary keys in updateData: must be NSStrings or FIRFieldPaths.");
  315. }
  316. value = self.preConverter(value);
  317. if ([value isKindOfClass:[FSTDeleteFieldValue class]]) {
  318. // Add it to the field mask, but don't add anything to updateData.
  319. [fieldMaskPaths addObject:path];
  320. } else {
  321. FSTFieldValue *_Nullable parsedValue =
  322. [self parseData:value context:[context contextForFieldPath:path]];
  323. if (parsedValue) {
  324. [fieldMaskPaths addObject:path];
  325. updateData = [updateData objectBySettingValue:parsedValue forPath:path];
  326. }
  327. }
  328. }];
  329. FSTFieldMask *mask = [[FSTFieldMask alloc] initWithFields:fieldMaskPaths];
  330. return [[FSTParsedUpdateData alloc] initWithData:updateData
  331. fieldMask:mask
  332. fieldTransforms:context.fieldTransforms];
  333. }
  334. - (FSTFieldValue *)parsedQueryValue:(id)input {
  335. FSTParseContext *context =
  336. [FSTParseContext contextWithSource:FSTUserDataSourceQueryValue path:[FSTFieldPath emptyPath]];
  337. FSTFieldValue *_Nullable parsed = [self parseData:input context:context];
  338. FSTAssert(parsed, @"Parsed data should not be nil.");
  339. FSTAssert(context.fieldTransforms.count == 0, @"Field transforms should have been disallowed.");
  340. return parsed;
  341. }
  342. /**
  343. * Internal helper for parsing user data.
  344. *
  345. * @param input Data to be parsed.
  346. * @param context A context object representing the current path being parsed, the source of the
  347. * data being parsed, etc.
  348. *
  349. * @return The parsed value, or nil if the value was a FieldValue sentinel that should not be
  350. * included in the resulting parsed data.
  351. */
  352. - (nullable FSTFieldValue *)parseData:(id)input context:(FSTParseContext *)context {
  353. input = self.preConverter(input);
  354. if ([input isKindOfClass:[NSArray class]]) {
  355. // TODO(b/34871131): Include the path containing the array in the error message.
  356. if (context.isArrayElement) {
  357. FSTThrowInvalidArgument(@"Nested arrays are not supported");
  358. }
  359. NSArray *array = input;
  360. NSMutableArray<FSTFieldValue *> *result = [NSMutableArray arrayWithCapacity:array.count];
  361. [array enumerateObjectsUsingBlock:^(id entry, NSUInteger idx, BOOL *stop) {
  362. FSTFieldValue *_Nullable parsedEntry =
  363. [self parseData:entry context:[context contextForArrayIndex:idx]];
  364. if (!parsedEntry) {
  365. // Just include nulls in the array for fields being replaced with a sentinel.
  366. parsedEntry = [FSTNullValue nullValue];
  367. }
  368. [result addObject:parsedEntry];
  369. }];
  370. // If context.path is nil we are already inside an array and we don't support field mask paths
  371. // more granular than the top-level array.
  372. if (context.path) {
  373. [context.fieldMask addObject:context.path];
  374. }
  375. return [[FSTArrayValue alloc] initWithValueNoCopy:result];
  376. } else if ([input isKindOfClass:[NSDictionary class]]) {
  377. NSDictionary *dict = input;
  378. NSMutableDictionary<NSString *, FSTFieldValue *> *result =
  379. [NSMutableDictionary dictionaryWithCapacity:dict.count];
  380. [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *stop) {
  381. FSTFieldValue *_Nullable parsedValue =
  382. [self parseData:value context:[context contextForField:key]];
  383. if (parsedValue) {
  384. result[key] = parsedValue;
  385. }
  386. }];
  387. return [[FSTObjectValue alloc] initWithDictionary:result];
  388. } else {
  389. // If context.path is null, we are inside an array and we should have already added the root of
  390. // the array to the field mask.
  391. if (context.path) {
  392. [context.fieldMask addObject:context.path];
  393. }
  394. return [self parseScalarValue:input context:context];
  395. }
  396. }
  397. /**
  398. * Helper to parse a scalar value (i.e. not an NSDictionary or NSArray).
  399. *
  400. * Note that it handles all NSNumber values that are encodable as int64_t or doubles
  401. * (depending on the underlying type of the NSNumber). Unsigned integer values are handled though
  402. * any value outside what is representable by int64_t (a signed 64-bit value) will throw an
  403. * exception.
  404. *
  405. * @return The parsed value, or nil if the value was a FieldValue sentinel that should not be
  406. * included in the resulting parsed data.
  407. */
  408. - (nullable FSTFieldValue *)parseScalarValue:(nullable id)input context:(FSTParseContext *)context {
  409. if (!input || [input isMemberOfClass:[NSNull class]]) {
  410. return [FSTNullValue nullValue];
  411. } else if ([input isKindOfClass:[NSNumber class]]) {
  412. // Recover the underlying type of the number, using the method described here:
  413. // http://stackoverflow.com/questions/2518761/get-type-of-nsnumber
  414. const char *cType = [input objCType];
  415. // Type Encoding values taken from
  416. // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/
  417. // Articles/ocrtTypeEncodings.html
  418. switch (cType[0]) {
  419. case 'q':
  420. return [FSTIntegerValue integerValue:[input longLongValue]];
  421. case 'i': // Falls through.
  422. case 's': // Falls through.
  423. case 'l': // Falls through.
  424. case 'I': // Falls through.
  425. case 'S':
  426. // Coerce integer values that aren't long long. Allow unsigned integer types that are
  427. // guaranteed small enough to skip a length check.
  428. return [FSTIntegerValue integerValue:[input longLongValue]];
  429. case 'L': // Falls through.
  430. case 'Q':
  431. // Unsigned integers that could be too large. Note that the 'L' (long) case is handled here
  432. // because when compiled for LP64, unsigned long is 64 bits and could overflow int64_t.
  433. {
  434. unsigned long long extended = [input unsignedLongLongValue];
  435. if (extended > LLONG_MAX) {
  436. FSTThrowInvalidArgument(@"NSNumber (%llu) is too large%@",
  437. [input unsignedLongLongValue], [context fieldDescription]);
  438. } else {
  439. return [FSTIntegerValue integerValue:(int64_t)extended];
  440. }
  441. }
  442. case 'f':
  443. return [FSTDoubleValue doubleValue:[input doubleValue]];
  444. case 'd':
  445. // Double values are already the right type, so just reuse the existing boxed double.
  446. //
  447. // Note that NSNumber already performs NaN normalization to a single shared instance
  448. // so there's no need to treat NaN specially here.
  449. return [FSTDoubleValue doubleValue:[input doubleValue]];
  450. case 'B': // Falls through.
  451. case 'c': // Falls through.
  452. case 'C':
  453. // Boolean values are weird.
  454. //
  455. // On arm64, objCType of a BOOL-valued NSNumber will be "c", even though @encode(BOOL)
  456. // returns "B". "c" is the same as @encode(signed char). Unfortunately this means that
  457. // legitimate usage of signed chars is impossible, but this should be rare.
  458. //
  459. // Additionally, for consistency, map unsigned chars to bools in the same way.
  460. return [FSTBooleanValue booleanValue:[input boolValue]];
  461. default:
  462. // All documented codes should be handled above, so this shouldn't happen.
  463. FSTCFail(@"Unknown NSNumber objCType %s on %@", cType, input);
  464. }
  465. } else if ([input isKindOfClass:[NSString class]]) {
  466. return [FSTStringValue stringValue:input];
  467. } else if ([input isKindOfClass:[NSDate class]]) {
  468. return [FSTTimestampValue timestampValue:[FIRTimestamp timestampWithDate:input]];
  469. } else if ([input isKindOfClass:[FIRTimestamp class]]) {
  470. FIRTimestamp *originalTimestamp = (FIRTimestamp *)input;
  471. FIRTimestamp *truncatedTimestamp =
  472. [FIRTimestamp timestampWithSeconds:originalTimestamp.seconds
  473. nanoseconds:originalTimestamp.nanoseconds / 1000 * 1000];
  474. return [FSTTimestampValue timestampValue:truncatedTimestamp];
  475. } else if ([input isKindOfClass:[FIRGeoPoint class]]) {
  476. return [FSTGeoPointValue geoPointValue:input];
  477. } else if ([input isKindOfClass:[NSData class]]) {
  478. return [FSTBlobValue blobValue:input];
  479. } else if ([input isKindOfClass:[FSTDocumentKeyReference class]]) {
  480. FSTDocumentKeyReference *reference = input;
  481. if (*reference.databaseID != *self.databaseID) {
  482. const DatabaseId *other = reference.databaseID;
  483. FSTThrowInvalidArgument(
  484. @"Document Reference is for database %@/%@ but should be for database %@/%@%@",
  485. util::WrapNSStringNoCopy(other->project_id()),
  486. util::WrapNSStringNoCopy(other->database_id()),
  487. util::WrapNSStringNoCopy(self.databaseID->project_id()),
  488. util::WrapNSStringNoCopy(self.databaseID->database_id()), [context fieldDescription]);
  489. }
  490. return [FSTReferenceValue referenceValue:reference.key databaseID:self.databaseID];
  491. } else if ([input isKindOfClass:[FIRFieldValue class]]) {
  492. if ([input isKindOfClass:[FSTDeleteFieldValue class]]) {
  493. if (context.dataSource == FSTUserDataSourceMergeSet) {
  494. return nil;
  495. } else if (context.dataSource == FSTUserDataSourceUpdate) {
  496. FSTAssert(context.path.length > 0,
  497. @"FieldValue.delete() at the top level should have already been handled.");
  498. FSTThrowInvalidArgument(
  499. @"FieldValue.delete() can only appear at the top level of your "
  500. "update data%@",
  501. [context fieldDescription]);
  502. } else {
  503. // We shouldn't encounter delete sentinels for queries or non-merge setData calls.
  504. FSTThrowInvalidArgument(
  505. @"FieldValue.delete() can only be used with updateData() and setData() with "
  506. @"SetOptions.merge().");
  507. }
  508. } else if ([input isKindOfClass:[FSTServerTimestampFieldValue class]]) {
  509. if (![context isWrite]) {
  510. FSTThrowInvalidArgument(
  511. @"FieldValue.serverTimestamp() can only be used with setData() and updateData().");
  512. }
  513. if (!context.path) {
  514. FSTThrowInvalidArgument(
  515. @"FieldValue.serverTimestamp() is not currently supported inside arrays%@",
  516. [context fieldDescription]);
  517. }
  518. [context.fieldTransforms
  519. addObject:[[FSTFieldTransform alloc]
  520. initWithPath:context.path
  521. transform:[FSTServerTimestampTransform serverTimestampTransform]]];
  522. // Return nil so this value is omitted from the parsed result.
  523. return nil;
  524. } else {
  525. FSTFail(@"Unknown FIRFieldValue type: %@", NSStringFromClass([input class]));
  526. }
  527. } else {
  528. FSTThrowInvalidArgument(@"Unsupported type: %@%@", NSStringFromClass([input class]),
  529. [context fieldDescription]);
  530. }
  531. }
  532. @end
  533. NS_ASSUME_NONNULL_END