FSTUserDataReader.mm 25 KB

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