FSTUserDataReader.mm 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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/FSTUserDataReader.h"
  17. #include <memory>
  18. #include <set>
  19. #include <string>
  20. #include <utility>
  21. #include <vector>
  22. #import "FIRGeoPoint.h"
  23. #import "FIRTimestamp.h"
  24. #import "Firestore/Source/API/FIRDocumentReference+Internal.h"
  25. #import "Firestore/Source/API/FIRFieldPath+Internal.h"
  26. #import "Firestore/Source/API/FIRFieldValue+Internal.h"
  27. #import "Firestore/Source/API/FIRFirestore+Internal.h"
  28. #import "Firestore/Source/API/FIRGeoPoint+Internal.h"
  29. #import "Firestore/Source/API/converters.h"
  30. #import "Firestore/core/include/firebase/firestore/geo_point.h"
  31. #include "Firestore/core/src/core/user_data.h"
  32. #include "Firestore/core/src/model/database_id.h"
  33. #include "Firestore/core/src/model/document_key.h"
  34. #include "Firestore/core/src/model/field_mask.h"
  35. #include "Firestore/core/src/model/field_path.h"
  36. #include "Firestore/core/src/model/field_transform.h"
  37. #include "Firestore/core/src/model/object_value.h"
  38. #include "Firestore/core/src/model/precondition.h"
  39. #include "Firestore/core/src/model/resource_path.h"
  40. #include "Firestore/core/src/model/transform_operation.h"
  41. #include "Firestore/core/src/model/value_util.h"
  42. #include "Firestore/core/src/nanopb/nanopb_util.h"
  43. #include "Firestore/core/src/nanopb/reader.h"
  44. #include "Firestore/core/src/remote/serializer.h"
  45. #include "Firestore/core/src/timestamp_internal.h"
  46. #include "Firestore/core/src/util/exception.h"
  47. #include "Firestore/core/src/util/hard_assert.h"
  48. #include "Firestore/core/src/util/read_context.h"
  49. #include "Firestore/core/src/util/string_apple.h"
  50. #include "absl/memory/memory.h"
  51. #include "absl/strings/match.h"
  52. #include "absl/types/optional.h"
  53. namespace nanopb = firebase::firestore::nanopb;
  54. using firebase::Timestamp;
  55. using firebase::TimestampInternal;
  56. using firebase::firestore::GeoPoint;
  57. using firebase::firestore::core::ParseAccumulator;
  58. using firebase::firestore::core::ParseContext;
  59. using firebase::firestore::core::ParsedSetData;
  60. using firebase::firestore::core::ParsedUpdateData;
  61. using firebase::firestore::core::UserDataSource;
  62. using firebase::firestore::model::ArrayTransform;
  63. using firebase::firestore::model::DatabaseId;
  64. using firebase::firestore::model::DocumentKey;
  65. using firebase::firestore::model::FieldMask;
  66. using firebase::firestore::model::FieldPath;
  67. using firebase::firestore::model::FieldTransform;
  68. using firebase::firestore::model::NullValue;
  69. using firebase::firestore::model::NumericIncrementTransform;
  70. using firebase::firestore::model::ObjectValue;
  71. using firebase::firestore::model::ResourcePath;
  72. using firebase::firestore::model::ServerTimestampTransform;
  73. using firebase::firestore::model::TransformOperation;
  74. using firebase::firestore::nanopb::CheckedSize;
  75. using firebase::firestore::nanopb::Message;
  76. using firebase::firestore::remote::Serializer;
  77. using firebase::firestore::util::MakeString;
  78. using firebase::firestore::util::ThrowInvalidArgument;
  79. using firebase::firestore::util::ReadContext;
  80. using firebase::firestore::google_firestore_v1_Value;
  81. using firebase::firestore::google_firestore_v1_MapValue;
  82. using firebase::firestore::google_firestore_v1_ArrayValue;
  83. using firebase::firestore::google_protobuf_NullValue_NULL_VALUE;
  84. using firebase::firestore::google_firestore_v1_MapValue_FieldsEntry;
  85. using firebase::firestore::google_type_LatLng;
  86. using firebase::firestore::google_protobuf_Timestamp;
  87. using nanopb::StringReader;
  88. NS_ASSUME_NONNULL_BEGIN
  89. #pragma mark - FSTDocumentKeyReference
  90. @implementation FSTDocumentKeyReference {
  91. DocumentKey _key;
  92. DatabaseId _databaseID;
  93. }
  94. - (instancetype)initWithKey:(DocumentKey)key databaseID:(DatabaseId)databaseID {
  95. self = [super init];
  96. if (self) {
  97. _key = std::move(key);
  98. _databaseID = std::move(databaseID);
  99. }
  100. return self;
  101. }
  102. - (const model::DocumentKey &)key {
  103. return _key;
  104. }
  105. - (const model::DatabaseId &)databaseID {
  106. return _databaseID;
  107. }
  108. @end
  109. #pragma mark - FSTUserDataReader
  110. @interface FSTUserDataReader ()
  111. @property(strong, nonatomic, readonly) FSTPreConverterBlock preConverter;
  112. @end
  113. @implementation FSTUserDataReader {
  114. DatabaseId _databaseID;
  115. }
  116. - (instancetype)initWithDatabaseID:(DatabaseId)databaseID
  117. preConverter:(FSTPreConverterBlock)preConverter {
  118. self = [super init];
  119. if (self) {
  120. _databaseID = std::move(databaseID);
  121. _preConverter = preConverter;
  122. }
  123. return self;
  124. }
  125. - (ParsedSetData)parsedSetData:(id)input {
  126. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  127. // Obj-C to verify the type for us.
  128. if (![input isKindOfClass:[NSDictionary class]]) {
  129. ThrowInvalidArgument("Data to be written must be an NSDictionary.");
  130. }
  131. ParseAccumulator accumulator{UserDataSource::Set};
  132. auto updateData = [self parseData:input context:accumulator.RootContext()];
  133. HARD_ASSERT(updateData.has_value(), "Parsed data should not be nil.");
  134. return std::move(accumulator).SetData(ObjectValue{std::move(*updateData)});
  135. }
  136. - (ParsedSetData)parsedMergeData:(id)input fieldMask:(nullable NSArray<id> *)fieldMask {
  137. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  138. // Obj-C to verify the type for us.
  139. if (![input isKindOfClass:[NSDictionary class]]) {
  140. ThrowInvalidArgument("Data to be written must be an NSDictionary.");
  141. }
  142. ParseAccumulator accumulator{UserDataSource::MergeSet};
  143. auto updateData = [self parseData:input context:accumulator.RootContext()];
  144. HARD_ASSERT(updateData.has_value(), "Parsed data should not be nil.");
  145. ObjectValue updateObject{std::move(*updateData)};
  146. if (fieldMask) {
  147. std::set<FieldPath> validatedFieldPaths;
  148. for (id fieldPath in fieldMask) {
  149. FieldPath path;
  150. if ([fieldPath isKindOfClass:[NSString class]]) {
  151. path = FieldPath::FromDotSeparatedString(MakeString(fieldPath));
  152. } else if ([fieldPath isKindOfClass:[FIRFieldPath class]]) {
  153. path = static_cast<FIRFieldPath *>(fieldPath).internalValue;
  154. } else {
  155. ThrowInvalidArgument("All elements in mergeFields: must be NSStrings or FIRFieldPaths.");
  156. }
  157. // Verify that all elements specified in the field mask are part of the parsed context.
  158. if (!accumulator.Contains(path)) {
  159. ThrowInvalidArgument(
  160. "Field '%s' is specified in your field mask but missing from your input data.",
  161. path.CanonicalString());
  162. }
  163. validatedFieldPaths.insert(path);
  164. }
  165. return std::move(accumulator)
  166. .MergeData(std::move(updateObject), FieldMask{std::move(validatedFieldPaths)});
  167. } else {
  168. return std::move(accumulator).MergeData(std::move(updateObject));
  169. }
  170. }
  171. - (ParsedUpdateData)parsedUpdateData:(id)input {
  172. // NOTE: The public API is typed as NSDictionary but we type 'input' as 'id' since we can't trust
  173. // Obj-C to verify the type for us.
  174. if (![input isKindOfClass:[NSDictionary class]]) {
  175. ThrowInvalidArgument("Data to be written must be an NSDictionary.");
  176. }
  177. NSDictionary *dict = input;
  178. ParseAccumulator accumulator{UserDataSource::Update};
  179. __block ParseContext context = accumulator.RootContext();
  180. __block ObjectValue updateData;
  181. [dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL *) {
  182. FieldPath path;
  183. if ([key isKindOfClass:[NSString class]]) {
  184. path = FieldPath::FromDotSeparatedString(MakeString(key));
  185. } else if ([key isKindOfClass:[FIRFieldPath class]]) {
  186. path = ((FIRFieldPath *)key).internalValue;
  187. } else {
  188. ThrowInvalidArgument("Dictionary keys in updateData: must be NSStrings or FIRFieldPaths.");
  189. }
  190. value = self.preConverter(value);
  191. if ([value isKindOfClass:[FSTDeleteFieldValue class]]) {
  192. // Add it to the field mask, but don't add anything to updateData.
  193. context.AddToFieldMask(std::move(path));
  194. } else {
  195. auto parsedValue = [self parseData:value context:context.ChildContext(path)];
  196. if (parsedValue) {
  197. context.AddToFieldMask(path);
  198. updateData.Set(path, std::move(*parsedValue));
  199. }
  200. }
  201. }];
  202. return std::move(accumulator).UpdateData(std::move(updateData));
  203. }
  204. - (Message<google_firestore_v1_Value>)parsedQueryValue:(id)input {
  205. return [self parsedQueryValue:input allowArrays:false];
  206. }
  207. - (Message<google_firestore_v1_Value>)parsedQueryValue:(id)input allowArrays:(bool)allowArrays {
  208. ParseAccumulator accumulator{allowArrays ? UserDataSource::ArrayArgument
  209. : UserDataSource::Argument};
  210. auto parsed = [self parseData:input context:accumulator.RootContext()];
  211. HARD_ASSERT(parsed, "Parsed data should not be nil.");
  212. HARD_ASSERT(accumulator.field_transforms().empty(),
  213. "Field transforms should have been disallowed.");
  214. return std::move(*parsed);
  215. }
  216. /**
  217. * Internal helper for parsing user data.
  218. *
  219. * @param input Data to be parsed.
  220. * @param context A context object representing the current path being parsed, the source of the
  221. * data being parsed, etc.
  222. *
  223. * @return The parsed value, or nil if the value was a FieldValue sentinel that should not be
  224. * included in the resulting parsed data.
  225. */
  226. - (absl::optional<Message<google_firestore_v1_Value>>)parseData:(id)input
  227. context:(ParseContext &&)context {
  228. input = self.preConverter(input);
  229. if ([input isKindOfClass:[NSDictionary class]]) {
  230. return [self parseDictionary:(NSDictionary *)input context:std::move(context)];
  231. } else if ([input isKindOfClass:[FIRFieldValue class]]) {
  232. // FieldValues usually parse into transforms (except FieldValue.delete()) in which case we
  233. // do not want to include this field in our parsed data (as doing so will overwrite the field
  234. // directly prior to the transform trying to transform it). So we don't call appendToFieldMask
  235. // and we return nil as our parsing result.
  236. [self parseSentinelFieldValue:(FIRFieldValue *)input context:std::move(context)];
  237. return absl::nullopt;
  238. } else {
  239. // If context path is unset we are already inside an array and we don't support field mask paths
  240. // more granular than the top-level array.
  241. if (context.path()) {
  242. context.AddToFieldMask(*context.path());
  243. }
  244. if ([input isKindOfClass:[NSArray class]]) {
  245. // TODO(b/34871131): Include the path containing the array in the error message.
  246. // In the case of IN queries, the parsed data is an array (representing the set of values to
  247. // be included for the IN query) that may directly contain additional arrays (each
  248. // representing an individual field value), so we disable this validation.
  249. if (context.array_element() && context.data_source() != UserDataSource::ArrayArgument) {
  250. ThrowInvalidArgument("Nested arrays are not supported");
  251. }
  252. return [self parseArray:(NSArray *)input context:std::move(context)];
  253. } else {
  254. return [self parseScalarValue:input context:std::move(context)];
  255. }
  256. }
  257. }
  258. - (Message<google_firestore_v1_Value>)parseDictionary:(NSDictionary<NSString *, id> *)dict
  259. context:(ParseContext &&)context {
  260. __block Message<google_firestore_v1_Value> result;
  261. result->which_value_type = google_firestore_v1_Value_map_value_tag;
  262. result->map_value = {};
  263. if (dict.count == 0) {
  264. const FieldPath *path = context.path();
  265. if (path && !path->empty()) {
  266. context.AddToFieldMask(*path);
  267. }
  268. } else {
  269. // Compute the final size of the fields array, which contains an entry for
  270. // all fields that are not FieldValue sentinels
  271. __block pb_size_t count = 0;
  272. [dict enumerateKeysAndObjectsUsingBlock:^(NSString *, id value, BOOL *) {
  273. if (![value isKindOfClass:[FIRFieldValue class]]) {
  274. ++count;
  275. }
  276. }];
  277. result->map_value.fields_count = count;
  278. result->map_value.fields = nanopb::MakeArray<google_firestore_v1_MapValue_FieldsEntry>(count);
  279. __block pb_size_t index = 0;
  280. [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, id value, BOOL *) {
  281. auto parsedValue = [self parseData:value context:context.ChildContext(MakeString(key))];
  282. if (parsedValue) {
  283. result->map_value.fields[index].key = nanopb::MakeBytesArray(MakeString(key));
  284. result->map_value.fields[index].value = *parsedValue->release();
  285. ++index;
  286. }
  287. }];
  288. }
  289. return std::move(result);
  290. }
  291. - (Message<google_firestore_v1_Value>)parseArray:(NSArray<id> *)array
  292. context:(ParseContext &&)context {
  293. __block Message<google_firestore_v1_Value> result;
  294. result->which_value_type = google_firestore_v1_Value_array_value_tag;
  295. result->array_value.values_count = CheckedSize([array count]);
  296. result->array_value.values =
  297. nanopb::MakeArray<google_firestore_v1_Value>(result->array_value.values_count);
  298. [array enumerateObjectsUsingBlock:^(id entry, NSUInteger idx, BOOL *) {
  299. auto parsedEntry = [self parseData:entry context:context.ChildContext(idx)];
  300. if (!parsedEntry) {
  301. // Just include nulls in the array for fields being replaced with a sentinel.
  302. parsedEntry = NullValue();
  303. }
  304. result->array_value.values[idx] = *parsedEntry->release();
  305. }];
  306. return std::move(result);
  307. }
  308. /**
  309. * "Parses" the provided FIRFieldValue, adding any necessary transforms to
  310. * context.fieldTransforms.
  311. */
  312. - (void)parseSentinelFieldValue:(FIRFieldValue *)fieldValue context:(ParseContext &&)context {
  313. // Sentinels are only supported with writes, and not within arrays.
  314. if (!context.write()) {
  315. ThrowInvalidArgument("%s can only be used with updateData() and setData()%s",
  316. fieldValue.methodName, context.FieldDescription());
  317. }
  318. if (!context.path()) {
  319. ThrowInvalidArgument("%s is not currently supported inside arrays", fieldValue.methodName);
  320. }
  321. if ([fieldValue isKindOfClass:[FSTDeleteFieldValue class]]) {
  322. if (context.data_source() == UserDataSource::MergeSet) {
  323. // No transform to add for a delete, but we need to add it to our fieldMask so it gets
  324. // deleted.
  325. context.AddToFieldMask(*context.path());
  326. } else if (context.data_source() == UserDataSource::Update) {
  327. HARD_ASSERT(!context.path()->empty(),
  328. "FieldValue.delete() at the top level should have already been handled.");
  329. ThrowInvalidArgument("FieldValue.delete() can only appear at the top level of your "
  330. "update data%s",
  331. context.FieldDescription());
  332. } else {
  333. // We shouldn't encounter delete sentinels for queries or non-merge setData calls.
  334. ThrowInvalidArgument(
  335. "FieldValue.delete() can only be used with updateData() and setData() with merge:true%s",
  336. context.FieldDescription());
  337. }
  338. } else if ([fieldValue isKindOfClass:[FSTServerTimestampFieldValue class]]) {
  339. context.AddToFieldTransforms(*context.path(), ServerTimestampTransform());
  340. } else if ([fieldValue isKindOfClass:[FSTArrayUnionFieldValue class]]) {
  341. auto parsedElements =
  342. [self parseArrayTransformElements:((FSTArrayUnionFieldValue *)fieldValue).elements];
  343. ArrayTransform arrayUnion(TransformOperation::Type::ArrayUnion, std::move(parsedElements));
  344. context.AddToFieldTransforms(*context.path(), std::move(arrayUnion));
  345. } else if ([fieldValue isKindOfClass:[FSTArrayRemoveFieldValue class]]) {
  346. auto parsedElements =
  347. [self parseArrayTransformElements:((FSTArrayRemoveFieldValue *)fieldValue).elements];
  348. ArrayTransform arrayRemove(TransformOperation::Type::ArrayRemove, std::move(parsedElements));
  349. context.AddToFieldTransforms(*context.path(), std::move(arrayRemove));
  350. } else if ([fieldValue isKindOfClass:[FSTNumericIncrementFieldValue class]]) {
  351. auto *numericIncrementFieldValue = (FSTNumericIncrementFieldValue *)fieldValue;
  352. auto operand = [self parsedQueryValue:numericIncrementFieldValue.operand];
  353. NumericIncrementTransform numeric_increment(std::move(operand));
  354. context.AddToFieldTransforms(*context.path(), std::move(numeric_increment));
  355. } else {
  356. HARD_FAIL("Unknown FIRFieldValue type: %s", NSStringFromClass([fieldValue class]));
  357. }
  358. }
  359. /**
  360. * Helper to parse a scalar value (i.e. not an NSDictionary, NSArray, or FIRFieldValue).
  361. *
  362. * Note that it handles all NSNumber values that are encodable as int64_t or doubles
  363. * (depending on the underlying type of the NSNumber). Unsigned integer values are handled though
  364. * any value outside what is representable by int64_t (a signed 64-bit value) will throw an
  365. * exception.
  366. *
  367. * @return The parsed value.
  368. */
  369. - (Message<google_firestore_v1_Value>)parseScalarValue:(nullable id)input
  370. context:(ParseContext &&)context {
  371. if (!input || [input isMemberOfClass:[NSNull class]]) {
  372. return NullValue();
  373. } else if ([input isKindOfClass:[NSNumber class]]) {
  374. // Recover the underlying type of the number, using the method described here:
  375. // http://stackoverflow.com/questions/2518761/get-type-of-nsnumber
  376. const char *cType = [input objCType];
  377. // Type Encoding values taken from
  378. // https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/
  379. // Articles/ocrtTypeEncodings.html
  380. switch (cType[0]) {
  381. case 'q':
  382. return [self encodeInteger:[input longLongValue]];
  383. case 'i': // Falls through.
  384. case 's': // Falls through.
  385. case 'l': // Falls through.
  386. case 'I': // Falls through.
  387. case 'S':
  388. // Coerce integer values that aren't long long. Allow unsigned integer types that are
  389. // guaranteed small enough to skip a length check.
  390. return [self encodeInteger:[input longLongValue]];
  391. case 'L': // Falls through.
  392. case 'Q':
  393. // Unsigned integers that could be too large. Note that the 'L' (long) case is handled here
  394. // because when compiled for LP64, unsigned long is 64 bits and could overflow int64_t.
  395. {
  396. unsigned long long extended = [input unsignedLongLongValue];
  397. if (extended > LLONG_MAX) {
  398. ThrowInvalidArgument("NSNumber (%s) is too large%s", [input unsignedLongLongValue],
  399. context.FieldDescription());
  400. } else {
  401. return [self encodeInteger:static_cast<int64_t>(extended)];
  402. }
  403. }
  404. case 'f':
  405. return [self encodeDouble:[input doubleValue]];
  406. case 'd':
  407. // Double values are already the right type, so just reuse the existing boxed double.
  408. //
  409. // Note that NSNumber already performs NaN normalization to a single shared instance
  410. // so there's no need to treat NaN specially here.
  411. return [self encodeDouble:[input doubleValue]];
  412. case 'B': // Falls through.
  413. case 'c': // Falls through.
  414. case 'C':
  415. // Boolean values are weird.
  416. //
  417. // On arm64, objCType of a BOOL-valued NSNumber will be "c", even though @encode(BOOL)
  418. // returns "B". "c" is the same as @encode(signed char). Unfortunately this means that
  419. // legitimate usage of signed chars is impossible, but this should be rare.
  420. //
  421. // Additionally, for consistency, map unsigned chars to bools in the same way.
  422. return [self encodeBoolean:[input boolValue]];
  423. default:
  424. // All documented codes should be handled above, so this shouldn't happen.
  425. HARD_FAIL("Unknown NSNumber objCType %s on %s", cType, input);
  426. }
  427. } else if ([input isKindOfClass:[NSString class]]) {
  428. std::string inputString = MakeString(input);
  429. return [self encodeStringValue:inputString];
  430. } else if ([input isKindOfClass:[NSDate class]]) {
  431. NSDate *inputDate = input;
  432. return [self encodeTimestampValue:api::MakeTimestamp(inputDate)];
  433. } else if ([input isKindOfClass:[FIRTimestamp class]]) {
  434. FIRTimestamp *inputTimestamp = input;
  435. Timestamp timestamp = TimestampInternal::Truncate(api::MakeTimestamp(inputTimestamp));
  436. return [self encodeTimestampValue:timestamp];
  437. } else if ([input isKindOfClass:[FIRGeoPoint class]]) {
  438. return [self encodeGeoPoint:api::MakeGeoPoint(input)];
  439. } else if ([input isKindOfClass:[NSData class]]) {
  440. NSData *inputData = input;
  441. return [self encodeBlob:(nanopb::MakeByteString(inputData))];
  442. } else if ([input isKindOfClass:[FSTDocumentKeyReference class]]) {
  443. FSTDocumentKeyReference *reference = input;
  444. if (reference.databaseID != _databaseID) {
  445. const DatabaseId &other = reference.databaseID;
  446. ThrowInvalidArgument(
  447. "Document Reference is for database %s/%s but should be for database %s/%s%s",
  448. other.project_id(), other.database_id(), _databaseID.project_id(),
  449. _databaseID.database_id(), context.FieldDescription());
  450. }
  451. return [self encodeReference:_databaseID key:reference.key];
  452. } else {
  453. ThrowInvalidArgument("Unsupported type: %s%s", NSStringFromClass([input class]),
  454. context.FieldDescription());
  455. }
  456. }
  457. - (Message<google_firestore_v1_Value>)encodeBoolean:(bool)value {
  458. Message<google_firestore_v1_Value> result;
  459. result->which_value_type = google_firestore_v1_Value_boolean_value_tag;
  460. result->boolean_value = value;
  461. return result;
  462. }
  463. - (Message<google_firestore_v1_Value>)encodeInteger:(int64_t)value {
  464. Message<google_firestore_v1_Value> result;
  465. result->which_value_type = google_firestore_v1_Value_integer_value_tag;
  466. result->integer_value = value;
  467. return result;
  468. }
  469. - (Message<google_firestore_v1_Value>)encodeDouble:(double)value {
  470. Message<google_firestore_v1_Value> result;
  471. result->which_value_type = google_firestore_v1_Value_double_value_tag;
  472. result->double_value = value;
  473. return result;
  474. }
  475. - (Message<google_firestore_v1_Value>)encodeTimestampValue:(Timestamp)value {
  476. Message<google_firestore_v1_Value> result;
  477. result->which_value_type = google_firestore_v1_Value_timestamp_value_tag;
  478. result->timestamp_value.seconds = value.seconds();
  479. result->timestamp_value.nanos = value.nanoseconds();
  480. return result;
  481. }
  482. - (Message<google_firestore_v1_Value>)encodeStringValue:(const std::string &)value {
  483. Message<google_firestore_v1_Value> result;
  484. result->which_value_type = google_firestore_v1_Value_string_value_tag;
  485. result->string_value = nanopb::MakeBytesArray(value);
  486. return result;
  487. }
  488. - (Message<google_firestore_v1_Value>)encodeBlob:(const nanopb::ByteString &)value {
  489. Message<google_firestore_v1_Value> result;
  490. result->which_value_type = google_firestore_v1_Value_bytes_value_tag;
  491. // Copy the blob so that pb_release can do the right thing.
  492. result->bytes_value = nanopb::CopyBytesArray(value.get());
  493. return result;
  494. }
  495. - (Message<google_firestore_v1_Value>)encodeReference:(const DatabaseId &)databaseId
  496. key:(const DocumentKey &)key {
  497. HARD_ASSERT(_databaseID == databaseId, "Database %s cannot encode reference from %s",
  498. _databaseID.ToString(), databaseId.ToString());
  499. std::string referenceName = ResourcePath({"projects", databaseId.project_id(), "databases",
  500. databaseId.database_id(), "documents", key.ToString()})
  501. .CanonicalString();
  502. Message<google_firestore_v1_Value> result;
  503. result->which_value_type = google_firestore_v1_Value_reference_value_tag;
  504. result->reference_value = nanopb::MakeBytesArray(referenceName);
  505. return result;
  506. }
  507. - (Message<google_firestore_v1_Value>)encodeGeoPoint:(const GeoPoint &)value {
  508. Message<google_firestore_v1_Value> result;
  509. result->which_value_type = google_firestore_v1_Value_geo_point_value_tag;
  510. result->geo_point_value.latitude = value.latitude();
  511. result->geo_point_value.longitude = value.longitude();
  512. return result;
  513. }
  514. - (Message<google_firestore_v1_ArrayValue>)parseArrayTransformElements:(NSArray<id> *)elements {
  515. ParseAccumulator accumulator{UserDataSource::Argument};
  516. Message<google_firestore_v1_ArrayValue> array_value;
  517. array_value->values_count = CheckedSize(elements.count);
  518. array_value->values = nanopb::MakeArray<google_firestore_v1_Value>(array_value->values_count);
  519. for (NSUInteger i = 0; i < elements.count; i++) {
  520. id element = elements[i];
  521. // Although array transforms are used with writes, the actual elements being unioned or removed
  522. // are not considered writes since they cannot contain any FieldValue sentinels, etc.
  523. ParseContext context = accumulator.RootContext();
  524. auto parsedElement = [self parseData:element context:context.ChildContext(i)];
  525. HARD_ASSERT(parsedElement && accumulator.field_transforms().empty(),
  526. "Failed to properly parse array transform element: %s", element);
  527. array_value->values[i] = *parsedElement->release();
  528. }
  529. return array_value;
  530. }
  531. @end
  532. NS_ASSUME_NONNULL_END