FSTUserDataConverter.m 23 KB

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