/
UpdateBuilder.java
621 lines (542 loc) · 21.5 KB
/
UpdateBuilder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
/*
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.firestore;
import com.google.api.core.ApiFunction;
import com.google.api.core.ApiFuture;
import com.google.api.core.ApiFutures;
import com.google.cloud.firestore.UserDataConverter.EncodingOptions;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.firestore.v1.CommitRequest;
import com.google.firestore.v1.CommitResponse;
import com.google.firestore.v1.Write;
import com.google.protobuf.ByteString;
import io.opencensus.trace.AttributeValue;
import io.opencensus.trace.Tracing;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* Abstract class that collects and bundles all write operations for {@link Transaction} and {@link
* WriteBatch}.
*/
public abstract class UpdateBuilder<T extends UpdateBuilder> {
final FirestoreImpl firestore;
private final List<Write.Builder> writes;
private boolean committed;
UpdateBuilder(FirestoreImpl firestore) {
this.firestore = firestore;
this.writes = new ArrayList<>();
}
/**
* Turns a field map that contains field paths into a nested map. Turns {a.b : c} into {a : {b :
* c}}.
*/
private static Map<String, Object> expandObject(Map<FieldPath, Object> data) {
Map<String, Object> result = new HashMap<>();
SortedSet<FieldPath> sortedFields = new TreeSet<>(data.keySet());
FieldPath lastField = null;
for (FieldPath field : sortedFields) {
if (lastField != null && lastField.isPrefixOf(field)) {
throw new IllegalArgumentException(
String.format("Detected ambiguous definition for field '%s'.", lastField));
}
List<String> segments = field.getSegments();
Object value = data.get(field);
Map<String, Object> currentMap = result;
for (int i = 0; i < segments.size(); ++i) {
if (i == segments.size() - 1) {
currentMap.put(segments.get(i), value);
} else {
if (!currentMap.containsKey(segments.get(i))) {
currentMap.put(segments.get(i), new HashMap<>());
}
currentMap = (Map<String, Object>) currentMap.get(segments.get(i));
}
}
lastField = field;
}
return result;
}
/**
* Creates a new Document at the DocumentReference's location. It fails the write if the document
* exists.
*
* @param documentReference The DocumentReference to create.
* @param fields A map of the fields and values for the document.
* @return The instance for chaining.
*/
@Nonnull
public T create(
@Nonnull DocumentReference documentReference, @Nonnull Map<String, Object> fields) {
return performCreate(documentReference, fields);
}
private T performCreate(
@Nonnull DocumentReference documentReference, @Nonnull Map<String, Object> fields) {
verifyNotCommitted();
DocumentSnapshot documentSnapshot =
DocumentSnapshot.fromObject(
firestore, documentReference, fields, UserDataConverter.NO_DELETES);
DocumentTransform documentTransform =
DocumentTransform.fromFieldPathMap(
documentReference, convertToFieldPaths(fields, /* splitOnDots= */ false));
Write.Builder write = documentSnapshot.toPb();
write.setCurrentDocument(Precondition.exists(false).toPb());
if (!documentTransform.isEmpty()) {
write.addAllUpdateTransforms(documentTransform.toPb());
}
writes.add(write);
return (T) this;
}
private void verifyNotCommitted() {
Preconditions.checkState(
!committed, "Cannot modify a WriteBatch that has already been committed.");
}
/**
* Creates a new Document at the DocumentReference location. It fails the write if the document
* exists.
*
* @param documentReference The DocumentReference to create.
* @param pojo The POJO that will be used to populate the document contents.
* @return The instance for chaining.
*/
@Nonnull
public T create(@Nonnull DocumentReference documentReference, @Nonnull Object pojo) {
Object data = CustomClassMapper.convertToPlainJavaTypes(pojo);
if (!(data instanceof Map)) {
throw FirestoreException.invalidState("Can't set a document's data to an array or primitive");
}
return performCreate(documentReference, (Map<String, Object>) data);
}
/**
* Overwrites the document referred to by this DocumentReference. If the document doesn't exist
* yet, it will be created. If a document already exists, it will be overwritten.
*
* @param documentReference The DocumentReference to overwrite.
* @param fields A map of the field paths and values for the document.
* @return The instance for chaining.
*/
@Nonnull
public T set(@Nonnull DocumentReference documentReference, @Nonnull Map<String, Object> fields) {
return set(documentReference, fields, SetOptions.OVERWRITE);
}
/**
* Overwrites the document referred to by this DocumentReference. If the document doesn't exist
* yet, it will be created. If you pass {@link SetOptions}, the provided data can be merged into
* an existing document.
*
* @param documentReference The DocumentReference to overwrite.
* @param fields A map of the field paths and values for the document.
* @param options An object to configure the set behavior.
* @return The instance for chaining.
*/
@Nonnull
public T set(
@Nonnull DocumentReference documentReference,
@Nonnull Map<String, Object> fields,
@Nonnull SetOptions options) {
return performSet(documentReference, fields, options);
}
/**
* Overwrites the document referred to by this DocumentReference. If the document doesn't exist
* yet, it will be created. If a document already exists, it will be overwritten.
*
* @param documentReference The DocumentReference to overwrite.
* @param pojo The POJO that will be used to populate the document contents.
* @return The instance for chaining.
*/
@Nonnull
public T set(@Nonnull DocumentReference documentReference, @Nonnull Object pojo) {
return set(documentReference, pojo, SetOptions.OVERWRITE);
}
/**
* Overwrites the document referred to by this DocumentReference. If the document doesn't exist
* yet, it will be created. If you pass {@link SetOptions}, the provided data can be merged into
* an existing document.
*
* @param documentReference The DocumentReference to overwrite.
* @param pojo The POJO that will be used to populate the document contents.
* @param options An object to configure the set behavior.
* @return The instance for chaining.
*/
@Nonnull
public T set(
@Nonnull DocumentReference documentReference,
@Nonnull Object pojo,
@Nonnull SetOptions options) {
Object data = CustomClassMapper.convertToPlainJavaTypes(pojo);
if (!(data instanceof Map)) {
throw new IllegalArgumentException("Can't set a document's data to an array or primitive");
}
return performSet(documentReference, (Map<String, Object>) data, options);
}
private T performSet(
@Nonnull DocumentReference documentReference,
@Nonnull Map<String, Object> fields,
@Nonnull SetOptions options) {
verifyNotCommitted();
Map<FieldPath, Object> documentData;
if (options.getFieldMask() != null) {
documentData = applyFieldMask(fields, options.getFieldMask());
} else {
documentData = convertToFieldPaths(fields, /* splitOnDots= */ false);
}
DocumentSnapshot documentSnapshot =
DocumentSnapshot.fromObject(
firestore, documentReference, expandObject(documentData), options.getEncodingOptions());
FieldMask documentMask = FieldMask.EMPTY_MASK;
DocumentTransform documentTransform =
DocumentTransform.fromFieldPathMap(documentReference, documentData);
if (options.getFieldMask() != null) {
List<FieldPath> fieldMask = new ArrayList<>(options.getFieldMask());
fieldMask.removeAll(documentTransform.getFields());
documentMask = new FieldMask(fieldMask);
} else if (options.isMerge()) {
documentMask = FieldMask.fromObject(fields);
}
Write.Builder write = documentSnapshot.toPb();
if (!documentTransform.isEmpty()) {
write.addAllUpdateTransforms(documentTransform.toPb());
}
if (options.isMerge() || options.getFieldMask() != null) {
write.setUpdateMask(documentMask.toPb());
}
writes.add(write);
return (T) this;
}
/** Removes all values in 'fields' that are not specified in 'fieldMask'. */
private Map<FieldPath, Object> applyFieldMask(
Map<String, Object> fields, List<FieldPath> fieldMask) {
List<FieldPath> remainingFields = new ArrayList<>(fieldMask);
Map<FieldPath, Object> filteredData =
applyFieldMask(fields, remainingFields, FieldPath.empty());
if (!remainingFields.isEmpty()) {
throw new IllegalArgumentException(
String.format(
"Field masks contains invalid path. No data exist at field '%s'.",
remainingFields.get(0)));
}
return filteredData;
}
/**
* Strips all values in 'fields' that are not specified in 'fieldMask'. Modifies 'fieldMask'
* inline and removes all matched fields.
*/
private Map<FieldPath, Object> applyFieldMask(
Map<String, Object> fields, List<FieldPath> fieldMask, FieldPath root) {
Map<FieldPath, Object> filteredMap = new HashMap<>();
for (Entry<String, Object> entry : fields.entrySet()) {
FieldPath currentField = root.append(FieldPath.of(entry.getKey()));
if (fieldMask.remove(currentField)) {
filteredMap.put(currentField, entry.getValue());
} else if (entry.getValue() instanceof Map) {
filteredMap.putAll(
applyFieldMask((Map<String, Object>) entry.getValue(), fieldMask, currentField));
} else if (entry.getValue() == FieldValue.DELETE_SENTINEL) {
throw new IllegalArgumentException(
String.format(
"Cannot specify FieldValue.delete() for non-merged field '%s'.", currentField));
}
}
return filteredMap;
}
private Map<FieldPath, Object> convertToFieldPaths(
@Nonnull Map<String, Object> fields, boolean splitOnDots) {
Map<FieldPath, Object> fieldPaths = new HashMap<>();
for (Map.Entry<String, Object> entry : fields.entrySet()) {
if (splitOnDots) {
fieldPaths.put(FieldPath.fromDotSeparatedString(entry.getKey()), entry.getValue());
} else {
fieldPaths.put(FieldPath.of(entry.getKey()), entry.getValue());
}
}
return fieldPaths;
}
/**
* Updates fields in the document referred to by this DocumentReference. If the document doesn't
* exist yet, the update will fail.
*
* @param documentReference The DocumentReference to update.
* @param fields A Map containing the fields and values with which to update the document.
* @return The instance for chaining.
*/
@Nonnull
public T update(
@Nonnull DocumentReference documentReference, @Nonnull Map<String, Object> fields) {
return performUpdate(
documentReference,
convertToFieldPaths(fields, /* splitOnDots= */ true),
Precondition.exists(true));
}
/**
* Updates fields in the document referred to by this DocumentReference. If the document doesn't
* exist yet, the update will fail.
*
* @param documentReference The DocumentReference to update.
* @param fields A Map containing the fields and values with which to update the document.
* @param options Preconditions to enforce on this update.
* @return The instance for chaining.
*/
@Nonnull
public T update(
@Nonnull DocumentReference documentReference,
@Nonnull Map<String, Object> fields,
Precondition options) {
Preconditions.checkArgument(
!options.hasExists(), "Precondition 'exists' cannot be specified for update() calls.");
return performUpdate(
documentReference, convertToFieldPaths(fields, /* splitOnDots= */ true), options);
}
/**
* Updates the fields in the document referred to by this DocumentReference. If the document
* doesn't exist yet, the update will fail.
*
* @param documentReference The DocumentReference to update.
* @param field The first field to set.
* @param value The first value to set.
* @param moreFieldsAndValues String and Object pairs with more fields to be set.
* @return The instance for chaining.
*/
@Nonnull
public T update(
@Nonnull DocumentReference documentReference,
@Nonnull String field,
@Nullable Object value,
Object... moreFieldsAndValues) {
return performUpdate(
documentReference,
Precondition.exists(true),
FieldPath.fromDotSeparatedString(field),
value,
moreFieldsAndValues);
}
/**
* Updates the fields in the document referred to by this DocumentReference. If the document
* doesn't exist yet, the update will fail.
*
* @param documentReference The DocumentReference to update.
* @param fieldPath The first field to set.
* @param value The first value to set.
* @param moreFieldsAndValues String and Object pairs with more fields to be set.
* @return The instance for chaining.
*/
@Nonnull
public T update(
@Nonnull DocumentReference documentReference,
@Nonnull FieldPath fieldPath,
@Nullable Object value,
Object... moreFieldsAndValues) {
return performUpdate(
documentReference, Precondition.exists(true), fieldPath, value, moreFieldsAndValues);
}
/**
* Updates the fields in the document referred to by this DocumentReference. If the document
* doesn't exist yet, the update will fail.
*
* @param documentReference The DocumentReference to update.
* @param options Preconditions to enforce on this update.
* @param field The first field to set.
* @param value The first value to set.
* @param moreFieldsAndValues String and Object pairs with more fields to be set.
* @return The instance for chaining.
*/
@Nonnull
public T update(
@Nonnull DocumentReference documentReference,
@Nonnull Precondition options,
@Nonnull String field,
@Nullable Object value,
Object... moreFieldsAndValues) {
Preconditions.checkArgument(
!options.hasExists(), "Precondition 'exists' cannot be specified for update() calls.");
return performUpdate(
documentReference,
options,
FieldPath.fromDotSeparatedString(field),
value,
moreFieldsAndValues);
}
/**
* Updates the fields in the document referred to by this DocumentReference. If the document
* doesn't exist yet, the update will fail.
*
* @param documentReference The DocumentReference to update.
* @param options Preconditions to enforce on this update.
* @param fieldPath The first field to set.
* @param value The first value to set.
* @param moreFieldsAndValues String and Object pairs with more fields to be set.
* @return The instance for chaining.
*/
@Nonnull
public T update(
@Nonnull DocumentReference documentReference,
@Nonnull Precondition options,
@Nonnull FieldPath fieldPath,
@Nullable Object value,
Object... moreFieldsAndValues) {
Preconditions.checkArgument(
!options.hasExists(), "Precondition 'exists' cannot be specified for update() calls.");
return performUpdate(documentReference, options, fieldPath, value, moreFieldsAndValues);
}
private T performUpdate(
@Nonnull DocumentReference documentReference,
@Nonnull Precondition options,
@Nonnull FieldPath fieldPath,
@Nullable Object value,
Object[] moreFieldsAndValues) {
Object data = CustomClassMapper.convertToPlainJavaTypes(value);
Map<FieldPath, Object> fields = new HashMap<>();
fields.put(fieldPath, data);
Preconditions.checkArgument(
moreFieldsAndValues.length % 2 == 0, "moreFieldsAndValues must be key-value pairs.");
for (int i = 0; i < moreFieldsAndValues.length; i += 2) {
Object objectPath = moreFieldsAndValues[i];
Object objectValue = moreFieldsAndValues[i + 1];
FieldPath currentPath;
if (objectPath instanceof String) {
currentPath = FieldPath.fromDotSeparatedString((String) objectPath);
} else if (objectPath instanceof FieldPath) {
currentPath = (FieldPath) objectPath;
} else {
throw new IllegalArgumentException(
"Field '" + objectPath + "' is not of type String or Field Path.");
}
if (fields.containsKey(currentPath)) {
throw new IllegalArgumentException(
"Field value for field '" + objectPath + "' was specified multiple times.");
}
fields.put(currentPath, objectValue);
}
return performUpdate(documentReference, fields, options);
}
private T performUpdate(
@Nonnull DocumentReference documentReference,
@Nonnull final Map<FieldPath, Object> fields,
@Nonnull Precondition precondition) {
verifyNotCommitted();
Preconditions.checkArgument(!fields.isEmpty(), "Data for update() cannot be empty.");
Map<String, Object> deconstructedMap = expandObject(fields);
DocumentSnapshot documentSnapshot =
DocumentSnapshot.fromObject(
firestore,
documentReference,
deconstructedMap,
new EncodingOptions() {
@Override
public boolean allowDelete(FieldPath fieldPath) {
return fields.containsKey(fieldPath);
}
@Override
public boolean allowTransform() {
return true;
}
});
List<FieldPath> fieldPaths = new ArrayList<>(fields.keySet());
DocumentTransform documentTransform =
DocumentTransform.fromFieldPathMap(documentReference, fields);
fieldPaths.removeAll(documentTransform.getFields());
FieldMask fieldMask = new FieldMask(fieldPaths);
Write.Builder write = documentSnapshot.toPb();
write.setCurrentDocument(precondition.toPb());
write.setUpdateMask(fieldMask.toPb());
if (!documentTransform.isEmpty()) {
write.addAllUpdateTransforms(documentTransform.toPb());
}
writes.add(write);
return (T) this;
}
/**
* Deletes the document referred to by this DocumentReference.
*
* @param documentReference The DocumentReference to delete.
* @param precondition Precondition for the delete operation.
* @return The instance for chaining.
*/
@Nonnull
public T delete(
@Nonnull DocumentReference documentReference, @Nonnull Precondition precondition) {
return performDelete(documentReference, precondition);
}
/**
* Deletes the document referred to by this DocumentReference.
*
* @param documentReference The DocumentReference to delete.
* @return The instance for chaining.
*/
@Nonnull
public T delete(@Nonnull DocumentReference documentReference) {
return performDelete(documentReference, Precondition.NONE);
}
private T performDelete(
@Nonnull DocumentReference documentReference, @Nonnull Precondition precondition) {
verifyNotCommitted();
Write.Builder write = Write.newBuilder().setDelete(documentReference.getName());
if (!precondition.isEmpty()) {
write.setCurrentDocument(precondition.toPb());
}
writes.add(write);
return (T) this;
}
/** Commit the current batch. */
ApiFuture<List<WriteResult>> commit(@Nullable ByteString transactionId) {
Tracing.getTracer()
.getCurrentSpan()
.addAnnotation(
"CloudFirestore.Commit",
ImmutableMap.of("numDocuments", AttributeValue.longAttributeValue(writes.size())));
final CommitRequest.Builder request = CommitRequest.newBuilder();
request.setDatabase(firestore.getDatabaseName());
for (Write.Builder write : writes) {
request.addWrites(write);
}
if (transactionId != null) {
request.setTransaction(transactionId);
}
committed = true;
ApiFuture<CommitResponse> response =
firestore.sendRequest(request.build(), firestore.getClient().commitCallable());
return ApiFutures.transform(
response,
new ApiFunction<CommitResponse, List<WriteResult>>() {
@Override
public List<WriteResult> apply(CommitResponse commitResponse) {
List<com.google.firestore.v1.WriteResult> writeResults =
commitResponse.getWriteResultsList();
List<WriteResult> result = new ArrayList<>();
for (com.google.firestore.v1.WriteResult writeResult : writeResults) {
result.add(WriteResult.fromProto(writeResult, commitResponse.getCommitTime()));
}
return result;
}
},
MoreExecutors.directExecutor());
}
/** Checks whether any updates have been queued. */
boolean isEmpty() {
return writes.isEmpty();
}
/** Get the number of writes. */
public int getMutationsSize() {
return writes.size();
}
}