/
DocumentReference.java
511 lines (470 loc) · 18 KB
/
DocumentReference.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
/*
* 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.api.core.InternalExtensionOnly;
import com.google.api.gax.rpc.ApiException;
import com.google.api.gax.rpc.ApiExceptions;
import com.google.cloud.firestore.v1.FirestoreClient.ListCollectionIdsPagedResponse;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.firestore.v1.ListCollectionIdsRequest;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Executor;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
/**
* A DocumentReference refers to a document location in a Firestore database and can be used to
* write, read, or listen to the location. There may or may not exist a document at the referenced
* location. A DocumentReference can also be used to create a CollectionReference to a
* subcollection.
*
* <p><b>Subclassing Note</b>: Firestore classes are not meant to be subclassed except for use in
* test mocks. Subclassing is not supported in production code and new SDK releases may break code
* that does so.
*/
@InternalExtensionOnly
public class DocumentReference {
private final ResourcePath path;
private final FirestoreRpcContext<?> rpcContext;
DocumentReference(
FirestoreRpcContext<?> rpcContext, ResourcePath path) { // Elevated access level for mocking.
this.path = path;
this.rpcContext = rpcContext;
}
/*
* Gets the Firestore instance associated with this document reference.
*
* @return The Firestore instance.
*/
@Nonnull
public Firestore getFirestore() {
return rpcContext.getFirestore();
}
/**
* The id of a document refers to the last component of path pointing to a document, e.g.
* "document-id" in "projects/project-id/databases/database-id/document-id".
*
* @return The ID of the document.
*/
@Nonnull
public String getId() {
return path.getId();
}
/**
* A string representing the path of the referenced document (relative to the root of the
* database).
*
* @return The slash-separated path relative to the root of the database.
*/
@Nonnull
public String getPath() {
return path.getPath();
}
/**
* A string representing the fully-qualified path of the referenced document.
*
* @return The fully-qualified path of the document.
*/
@Nonnull
String getName() {
return path.getName();
}
/**
* A reference to the Collection to which this DocumentReference belongs to.
*
* @return The parent Collection.
*/
@Nonnull
public CollectionReference getParent() {
return new CollectionReference(rpcContext, path.getParent());
}
/**
* Gets a CollectionReference instance that refers to the collection that is a child of this
* document.
*
* @param collectionPath A relative and slash-separated path to a collection.
* @return The CollectionReference instance.
*/
@Nonnull
public CollectionReference collection(@Nonnull String collectionPath) {
return new CollectionReference(rpcContext, path.append(collectionPath));
}
/**
* Extracts the first result from an ApiFuture with list of results.
*
* @param results A list with results.
* @return An ApiFuture with the first WriteResult.
*/
private <T> ApiFuture<T> extractFirst(ApiFuture<List<T>> results) {
return ApiFutures.transform(
results,
new ApiFunction<List<T>, T>() {
@Override
public T apply(List<T> results) {
return results.isEmpty() ? null : results.get(0);
}
},
MoreExecutors.directExecutor());
}
/**
* Creates a new Document at the DocumentReference's Location. It fails the write if the document
* exists.
*
* @param fields A map of the fields and values for the document.
* @return An ApiFuture that will be resolved when the write finishes.
*/
@Nonnull
public ApiFuture<WriteResult> create(@Nonnull Map<String, Object> fields) {
WriteBatch writeBatch = rpcContext.getFirestore().batch();
return extractFirst(writeBatch.create(this, fields).commit());
}
/**
* Creates a new Document at the DocumentReference location. It fails the write if the document
* exists.
*
* @param pojo The POJO that will be used to populate the document contents.
* @return An ApiFuture that will be resolved when the write finishes.
*/
@Nonnull
public ApiFuture<WriteResult> create(@Nonnull Object pojo) {
WriteBatch writeBatch = rpcContext.getFirestore().batch();
return extractFirst(writeBatch.create(this, pojo).commit());
}
/**
* Overwrites the document referred to by this DocumentReference. If no document exists yet, it
* will be created. If a document already exists, it will be overwritten.
*
* @param fields A map of the fields and values for the document.
* @return An ApiFuture that will be resolved when the write finishes.
*/
@Nonnull
public ApiFuture<WriteResult> set(@Nonnull Map<String, Object> fields) {
WriteBatch writeBatch = rpcContext.getFirestore().batch();
return extractFirst(writeBatch.set(this, fields).commit());
}
/**
* Writes to the document referred to by this DocumentReference. If the document does not yet
* exist, it will be created. If you pass {@link SetOptions}, the provided data can be merged into
* an existing document.
*
* @param fields A map of the fields and values for the document.
* @param options An object to configure the set behavior.
* @return An ApiFuture that will be resolved when the write finishes.
*/
@Nonnull
public ApiFuture<WriteResult> set(
@Nonnull Map<String, Object> fields, @Nonnull SetOptions options) {
WriteBatch writeBatch = rpcContext.getFirestore().batch();
return extractFirst(writeBatch.set(this, fields, options).commit());
}
/**
* Overwrites the document referred to by this DocumentReference. If no document exists yet, it
* will be created. If a document already exists, it will be overwritten.
*
* @param pojo The POJO that will be used to populate the document contents.
* @return An ApiFuture that will be resolved when the write finishes.
*/
@Nonnull
public ApiFuture<WriteResult> set(@Nonnull Object pojo) {
WriteBatch writeBatch = rpcContext.getFirestore().batch();
return extractFirst(writeBatch.set(this, pojo).commit());
}
/**
* Writes to the document referred to by this DocumentReference. If the document does not yet
* exist, it will be created. If you pass {@link SetOptions}, the provided data can be merged into
* an existing document.
*
* @param pojo The POJO that will be used to populate the document contents.
* @param options An object to configure the set behavior.
* @return An ApiFuture that will be resolved when the write finishes.
*/
@Nonnull
public ApiFuture<WriteResult> set(@Nonnull Object pojo, @Nonnull SetOptions options) {
WriteBatch writeBatch = rpcContext.getFirestore().batch();
return extractFirst(writeBatch.set(this, pojo, options).commit());
}
/**
* Updates fields in the document referred to by this DocumentReference. If the document doesn't
* exist yet, the update will fail.
*
* @param fields A Map containing the fields and values with which to update the document.
* @return An ApiFuture that will be resolved when the write finishes.
*/
@Nonnull
public ApiFuture<WriteResult> update(@Nonnull Map<String, Object> fields) {
WriteBatch writeBatch = rpcContext.getFirestore().batch();
return extractFirst(writeBatch.update(this, fields).commit());
}
/**
* Updates fields in the document referred to by this DocumentReference. If the document doesn't
* exist yet, the update will fail.
*
* @param fields A map containing the fields and values with which to update the document.
* @param options Preconditions to enforce on this update.
* @return An ApiFuture that will be resolved when the write finishes.
*/
@Nonnull
public ApiFuture<WriteResult> update(@Nonnull Map<String, Object> fields, Precondition options) {
WriteBatch writeBatch = rpcContext.getFirestore().batch();
return extractFirst(writeBatch.update(this, fields, options).commit());
}
/**
* Updates the fields in the document referred to by this DocumentReference. If the document
* doesn't exist yet, the update will fail.
*
* @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 An ApiFuture that will be resolved when the write finishes.
*/
@Nonnull
public ApiFuture<WriteResult> update(
@Nonnull String field, @Nullable Object value, Object... moreFieldsAndValues) {
WriteBatch writeBatch = rpcContext.getFirestore().batch();
return extractFirst(writeBatch.update(this, field, value, moreFieldsAndValues).commit());
}
/**
* Updates the fields in the document referred to by this DocumentReference. If the document
* doesn't exist yet, the update will fail.
*
* @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 A ApiFuture that will be resolved when the write finishes.
*/
@Nonnull
public ApiFuture<WriteResult> update(
@Nonnull FieldPath fieldPath, @Nullable Object value, Object... moreFieldsAndValues) {
WriteBatch writeBatch = rpcContext.getFirestore().batch();
return extractFirst(writeBatch.update(this, fieldPath, value, moreFieldsAndValues).commit());
}
/**
* Updates the fields in the document referred to by this DocumentReference. If the document
* doesn't exist yet, the update will fail.
*
* @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 A ApiFuture that will be resolved when the write finishes.
*/
@Nonnull
public ApiFuture<WriteResult> update(
@Nonnull Precondition options,
@Nonnull String field,
@Nullable Object value,
Object... moreFieldsAndValues) {
WriteBatch writeBatch = rpcContext.getFirestore().batch();
return extractFirst(
writeBatch.update(this, options, field, value, moreFieldsAndValues).commit());
}
/**
* Updates the fields in the document referred to by this DocumentReference. If the document
* doesn't exist yet, the update will fail.
*
* @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 A ApiFuture that will be resolved when the write finishes.
*/
@Nonnull
public ApiFuture<WriteResult> update(
@Nonnull Precondition options,
@Nonnull FieldPath fieldPath,
@Nullable Object value,
Object... moreFieldsAndValues) {
WriteBatch writeBatch = rpcContext.getFirestore().batch();
return extractFirst(
writeBatch.update(this, options, fieldPath, value, moreFieldsAndValues).commit());
}
/**
* Deletes the document referred to by this DocumentReference.
*
* @param options Preconditions to enforce for this delete.
* @return An ApiFuture that will be resolved when the delete completes.
*/
@Nonnull
public ApiFuture<WriteResult> delete(@Nonnull Precondition options) {
WriteBatch writeBatch = rpcContext.getFirestore().batch();
return extractFirst(writeBatch.delete(this, options).commit());
}
/**
* Deletes the document referred to by this DocumentReference.
*
* @return An ApiFuture that will be resolved when the delete completes.
*/
@Nonnull
public ApiFuture<WriteResult> delete() {
WriteBatch writeBatch = rpcContext.getFirestore().batch();
return extractFirst(writeBatch.delete(this).commit());
}
/**
* Reads the document referenced by this DocumentReference. If the document doesn't exist, the
* get() will return an an empty DocumentSnapshot.
*
* @return An ApiFuture that will be resolved with the contents of the Document at this
* DocumentReference, or a failure if the document does not exist.
*/
@Nonnull
public ApiFuture<DocumentSnapshot> get() {
return extractFirst(rpcContext.getFirestore().getAll(this));
}
/**
* Reads the document referenced by this DocumentReference. If the document doesn't exist, the
* get(FieldMask fieldMask) will return an empty DocumentSnapshot.
*
* @param fieldMask A FieldMask object to retrieve the field value
* @return An ApiFuture that will be resolved with the contents of the Document at this
* DocumentReference, or a failure if the document does not exist
*/
@Nonnull
public ApiFuture<DocumentSnapshot> get(FieldMask fieldMask) {
return extractFirst(
rpcContext.getFirestore().getAll(new DocumentReference[] {this}, fieldMask));
}
/**
* Fetches the subcollections that are direct children of this document.
*
* @throws FirestoreException if the Iterable could not be initialized.
* @return An Iterable that can be used to fetch all subcollections.
*/
@Nonnull
public Iterable<CollectionReference> listCollections() {
ListCollectionIdsRequest.Builder request = ListCollectionIdsRequest.newBuilder();
request.setParent(path.toString());
final ListCollectionIdsPagedResponse response;
try {
response =
ApiExceptions.callAndTranslateApiException(
rpcContext.sendRequest(
request.build(), rpcContext.getClient().listCollectionIdsPagedCallable()));
} catch (ApiException exception) {
throw FirestoreException.apiException(exception);
}
return new Iterable<CollectionReference>() {
@Override
@Nonnull
public Iterator<CollectionReference> iterator() {
final Iterator<String> iterator = response.iterateAll().iterator();
return new Iterator<CollectionReference>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public CollectionReference next() {
return DocumentReference.this.collection(iterator.next());
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
};
}
};
}
/**
* Fetches the subcollections that are direct children of this document.
*
* @deprecated Use {@link #listCollections()}.
* @throws FirestoreException if the Iterable could not be initialized.
* @return An Iterable that can be used to fetch all subcollections.
*/
@Deprecated
@Nonnull
public Iterable<CollectionReference> getCollections() {
return listCollections();
}
/**
* Starts listening to the document referenced by this DocumentReference.
*
* @param executor The executor to use to call the listener.
* @param listener The event listener that will be called with the snapshots.
* @return A registration object that can be used to remove the listener.
*/
@Nonnull
public ListenerRegistration addSnapshotListener(
@Nonnull Executor executor, @Nonnull final EventListener<DocumentSnapshot> listener) {
return Watch.forDocument(this)
.runWatch(
executor,
new EventListener<QuerySnapshot>() {
@Override
public void onEvent(
@Nullable QuerySnapshot value, @Nullable FirestoreException error) {
if (value == null) {
listener.onEvent(null, error);
return;
}
for (DocumentSnapshot doc : value) {
if (doc.getReference().equals(DocumentReference.this)) {
listener.onEvent(value.getDocuments().get(0), null);
return;
}
}
listener.onEvent(
DocumentSnapshot.fromMissing(
rpcContext, DocumentReference.this, value.getReadTime()),
null);
}
});
}
/**
* Starts listening to the document referenced by this DocumentReference.
*
* @param listener The event listener that will be called with the snapshots.
* @return A registration object that can be used to remove the listener.
*/
@Nonnull
public ListenerRegistration addSnapshotListener(
@Nonnull EventListener<DocumentSnapshot> listener) {
return addSnapshotListener(rpcContext.getClient().getExecutor(), listener);
}
ResourcePath getResourcePath() {
return path;
}
@Override
public String toString() {
return String.format("DocumentReference{path=%s}", path);
}
/**
* Returns true if this DocumentReference is equal to the provided object.
*
* @param obj The object to compare against.
* @return Whether this DocumentReference is equal to the provided object.
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
DocumentReference that = (DocumentReference) obj;
return Objects.equals(path, that.path) && Objects.equals(rpcContext, that.rpcContext);
}
@Override
public int hashCode() {
return Objects.hash(path, rpcContext);
}
}