Search in sources :

Example 11 with Document

use of com.google.firebase.firestore.model.Document in project firebase-android-sdk by firebase.

the class SyncEngine method handleRemoteEvent.

/**
 * Called by FirestoreClient to notify us of a new remote event.
 */
@Override
public void handleRemoteEvent(RemoteEvent event) {
    assertCallback("handleRemoteEvent");
    // Update `receivedDocument` as appropriate for any limbo targets.
    for (Map.Entry<Integer, TargetChange> entry : event.getTargetChanges().entrySet()) {
        Integer targetId = entry.getKey();
        TargetChange targetChange = entry.getValue();
        LimboResolution limboResolution = activeLimboResolutionsByTarget.get(targetId);
        if (limboResolution != null) {
            // Since this is a limbo resolution lookup, it's for a single document and it could be
            // added, modified, or removed, but not a combination.
            hardAssert(targetChange.getAddedDocuments().size() + targetChange.getModifiedDocuments().size() + targetChange.getRemovedDocuments().size() <= 1, "Limbo resolution for single document contains multiple changes.");
            if (targetChange.getAddedDocuments().size() > 0) {
                limboResolution.receivedDocument = true;
            } else if (targetChange.getModifiedDocuments().size() > 0) {
                hardAssert(limboResolution.receivedDocument, "Received change for limbo target document without add.");
            } else if (targetChange.getRemovedDocuments().size() > 0) {
                hardAssert(limboResolution.receivedDocument, "Received remove for limbo target document without add.");
                limboResolution.receivedDocument = false;
            } else {
            // This was probably just a CURRENT targetChange or similar.
            }
        }
    }
    ImmutableSortedMap<DocumentKey, Document> changes = localStore.applyRemoteEvent(event);
    emitNewSnapsAndNotifyLocalStore(changes, event);
}
Also used : TargetChange(com.google.firebase.firestore.remote.TargetChange) DocumentKey(com.google.firebase.firestore.model.DocumentKey) Document(com.google.firebase.firestore.model.Document) MutableDocument(com.google.firebase.firestore.model.MutableDocument) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableSortedMap(com.google.firebase.database.collection.ImmutableSortedMap)

Example 12 with Document

use of com.google.firebase.firestore.model.Document in project firebase-android-sdk by firebase.

the class Query method boundFromDocumentSnapshot.

/**
 * Create a Bound from a query given the document.
 *
 * <p>Note that the Bound will always include the key of the document and so only the provided
 * document will compare equal to the returned position.
 *
 * <p>Will throw if the document does not contain all fields of the order by of the query or if
 * any of the fields in the order by are an uncommitted server timestamp.
 */
private Bound boundFromDocumentSnapshot(String methodName, DocumentSnapshot snapshot, boolean inclusive) {
    checkNotNull(snapshot, "Provided snapshot must not be null.");
    if (!snapshot.exists()) {
        throw new IllegalArgumentException("Can't use a DocumentSnapshot for a document that doesn't exist for " + methodName + "().");
    }
    Document document = snapshot.getDocument();
    List<Value> components = new ArrayList<>();
    // orders), multiple documents could match the position, yielding duplicate results.
    for (OrderBy orderBy : query.getOrderBy()) {
        if (orderBy.getField().equals(com.google.firebase.firestore.model.FieldPath.KEY_PATH)) {
            components.add(Values.refValue(firestore.getDatabaseId(), document.getKey()));
        } else {
            Value value = document.getField(orderBy.getField());
            if (ServerTimestamps.isServerTimestamp(value)) {
                throw new IllegalArgumentException("Invalid query. You are trying to start or end a query using a document for which " + "the field '" + orderBy.getField() + "' is an uncommitted server timestamp. (Since the value of this field is " + "unknown, you cannot start/end a query with it.)");
            } else if (value != null) {
                components.add(value);
            } else {
                throw new IllegalArgumentException("Invalid query. You are trying to start or end a query using a document for which " + "the field '" + orderBy.getField() + "' (used as the orderBy) does not exist.");
            }
        }
    }
    return new Bound(components, inclusive);
}
Also used : OrderBy(com.google.firebase.firestore.core.OrderBy) Value(com.google.firestore.v1.Value) ArrayValue(com.google.firestore.v1.ArrayValue) ArrayList(java.util.ArrayList) Bound(com.google.firebase.firestore.core.Bound) Document(com.google.firebase.firestore.model.Document)

Example 13 with Document

use of com.google.firebase.firestore.model.Document in project firebase-android-sdk by firebase.

the class LocalStoreTestCase method assertContains.

/**
 * Asserts that the given local store contains the given document.
 */
private void assertContains(MutableDocument expected) {
    Document actual = localStore.readDocument(expected.getKey());
    assertEquals(expected, actual);
}
Also used : Document(com.google.firebase.firestore.model.Document) MutableDocument(com.google.firebase.firestore.model.MutableDocument)

Example 14 with Document

use of com.google.firebase.firestore.model.Document in project firebase-android-sdk by firebase.

the class ViewTest method testAddsDocumentsBasedOnQuery.

@Test
public void testAddsDocumentsBasedOnQuery() {
    Query query = messageQuery();
    View view = new View(query, DocumentKey.emptyKeySet());
    MutableDocument doc1 = doc("rooms/eros/messages/1", 0, map("text", "msg1"));
    MutableDocument doc2 = doc("rooms/eros/messages/2", 0, map("text", "msg2"));
    MutableDocument doc3 = doc("rooms/other/messages/1", 0, map("text", "msg3"));
    ImmutableSortedMap<DocumentKey, Document> updates = docUpdates(doc1, doc2, doc3);
    View.DocumentChanges docViewChanges = view.computeDocChanges(updates);
    TargetChange targetChange = ackTarget(doc1, doc2, doc3);
    ViewSnapshot snapshot = view.applyChanges(docViewChanges, targetChange).getSnapshot();
    assertEquals(query, snapshot.getQuery());
    assertEquals(asList(doc1, doc2), snapshot.getDocuments().toList());
    assertEquals(asList(DocumentViewChange.create(Type.ADDED, doc1), DocumentViewChange.create(Type.ADDED, doc2)), snapshot.getChanges());
    assertFalse(snapshot.isFromCache());
    assertTrue(snapshot.didSyncStateChange());
    assertFalse(snapshot.hasPendingWrites());
}
Also used : TargetChange(com.google.firebase.firestore.remote.TargetChange) MutableDocument(com.google.firebase.firestore.model.MutableDocument) DocumentKey(com.google.firebase.firestore.model.DocumentKey) Document(com.google.firebase.firestore.model.Document) MutableDocument(com.google.firebase.firestore.model.MutableDocument) Test(org.junit.Test)

Example 15 with Document

use of com.google.firebase.firestore.model.Document in project firebase-android-sdk by firebase.

the class SyncEngine method loadBundle.

public void loadBundle(BundleReader bundleReader, LoadBundleTask resultTask) {
    try {
        BundleMetadata bundleMetadata = bundleReader.getBundleMetadata();
        boolean hasNewerBundle = localStore.hasNewerBundle(bundleMetadata);
        if (hasNewerBundle) {
            resultTask.setResult(LoadBundleTaskProgress.forSuccess(bundleMetadata));
            return;
        }
        @Nullable LoadBundleTaskProgress progress = LoadBundleTaskProgress.forInitial(bundleMetadata);
        resultTask.updateProgress(progress);
        BundleLoader bundleLoader = new BundleLoader(localStore, bundleMetadata);
        long currentBytesRead = 0;
        BundleElement bundleElement;
        while ((bundleElement = bundleReader.getNextElement()) != null) {
            long oldBytesRead = currentBytesRead;
            currentBytesRead = bundleReader.getBytesRead();
            progress = bundleLoader.addElement(bundleElement, currentBytesRead - oldBytesRead);
            if (progress != null) {
                resultTask.updateProgress(progress);
            }
        }
        ImmutableSortedMap<DocumentKey, Document> changes = bundleLoader.applyChanges();
        // TODO(b/160876443): This currently raises snapshots with `fromCache=false` if users already
        // listen to some queries and bundles has newer version.
        emitNewSnapsAndNotifyLocalStore(changes, /* remoteEvent= */
        null);
        // Save metadata, so loading the same bundle will skip.
        localStore.saveBundle(bundleMetadata);
        resultTask.setResult(LoadBundleTaskProgress.forSuccess(bundleMetadata));
    } catch (Exception e) {
        Logger.warn("Firestore", "Loading bundle failed : %s", e);
        resultTask.setException(new FirebaseFirestoreException("Bundle failed to load", FirebaseFirestoreException.Code.INVALID_ARGUMENT, e));
    } finally {
        try {
            bundleReader.close();
        } catch (IOException e) {
            Logger.warn("SyncEngine", "Exception while closing bundle", e);
        }
    }
}
Also used : BundleElement(com.google.firebase.firestore.bundle.BundleElement) FirebaseFirestoreException(com.google.firebase.firestore.FirebaseFirestoreException) IOException(java.io.IOException) Document(com.google.firebase.firestore.model.Document) MutableDocument(com.google.firebase.firestore.model.MutableDocument) FirebaseFirestoreException(com.google.firebase.firestore.FirebaseFirestoreException) IOException(java.io.IOException) BundleMetadata(com.google.firebase.firestore.bundle.BundleMetadata) DocumentKey(com.google.firebase.firestore.model.DocumentKey) LoadBundleTaskProgress(com.google.firebase.firestore.LoadBundleTaskProgress) Nullable(androidx.annotation.Nullable) BundleLoader(com.google.firebase.firestore.bundle.BundleLoader)

Aggregations

Document (com.google.firebase.firestore.model.Document)29 DocumentKey (com.google.firebase.firestore.model.DocumentKey)23 MutableDocument (com.google.firebase.firestore.model.MutableDocument)21 Map (java.util.Map)8 ImmutableSortedMap (com.google.firebase.database.collection.ImmutableSortedMap)7 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)6 DocumentCollections.emptyDocumentMap (com.google.firebase.firestore.model.DocumentCollections.emptyDocumentMap)4 Query (com.google.firebase.firestore.core.Query)3 Overlay (com.google.firebase.firestore.model.mutation.Overlay)3 TargetChange (com.google.firebase.firestore.remote.TargetChange)3 NonNull (androidx.annotation.NonNull)2 Nullable (androidx.annotation.Nullable)2 Task (com.google.android.gms.tasks.Task)2 Timestamp (com.google.firebase.Timestamp)2 View (com.google.firebase.firestore.core.View)2 ViewSnapshot (com.google.firebase.firestore.core.ViewSnapshot)2 DocumentSet (com.google.firebase.firestore.model.DocumentSet)2 ResourcePath (com.google.firebase.firestore.model.ResourcePath)2 DeleteMutation (com.google.firebase.firestore.model.mutation.DeleteMutation)2