Search in sources :

Example 66 with DocumentKey

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

the class WatchChangeAggregator method resetTarget.

/**
 * Resets the state of a Watch target to its initial state (e.g. sets 'current' to false, clears
 * the resume token and removes its target mapping from all documents).
 */
private void resetTarget(int targetId) {
    hardAssert(targetStates.get(targetId) != null && !targetStates.get(targetId).isPending(), "Should only reset active targets");
    targetStates.put(targetId, new TargetState());
    // Trigger removal for any documents currently mapped to this target. These removals will be
    // part of the initial snapshot if Watch does not resend these documents.
    ImmutableSortedSet<DocumentKey> existingKeys = targetMetadataProvider.getRemoteKeysForTarget(targetId);
    for (DocumentKey key : existingKeys) {
        removeDocumentFromTarget(targetId, key, null);
    }
}
Also used : DocumentKey(com.google.firebase.firestore.model.DocumentKey)

Example 67 with DocumentKey

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

the class MutationBatch method applyToLocalDocumentSet.

/**
 * Computes the local view for all provided documents given the mutations in this batch. Returns a
 * {@code DocumentKey} to {@code Mutation} map which can be used to replace all the mutation
 * applications.
 */
public Map<DocumentKey, Mutation> applyToLocalDocumentSet(Map<DocumentKey, OverlayedDocument> documentMap, Set<DocumentKey> documentsWithoutRemoteVersion) {
    // TODO(mrschmidt): This implementation is O(n^2). If we iterate through the mutations first
    // (as done in `applyToLocalView(MutableDocument d)`), we can reduce the complexity to
    // O(n).
    Map<DocumentKey, Mutation> overlays = new HashMap<>();
    for (DocumentKey key : getKeys()) {
        // TODO(mutabledocuments): This method should take a map of MutableDocuments and we should
        // remove this cast.
        MutableDocument document = (MutableDocument) documentMap.get(key).getDocument();
        FieldMask mutatedFields = applyToLocalView(document, documentMap.get(key).getMutatedFields());
        // Set mutationFields to null if the document is only from local mutations, this creates
        // a Set(or Delete) mutation, instead of trying to create a patch mutation as the overlay.
        mutatedFields = documentsWithoutRemoteVersion.contains(key) ? null : mutatedFields;
        Mutation overlay = Mutation.calculateOverlayMutation(document, mutatedFields);
        if (overlay != null) {
            overlays.put(key, overlay);
        }
        if (!document.isValidDocument()) {
            document.convertToNoDocument(SnapshotVersion.NONE);
        }
    }
    return overlays;
}
Also used : HashMap(java.util.HashMap) DocumentKey(com.google.firebase.firestore.model.DocumentKey) MutableDocument(com.google.firebase.firestore.model.MutableDocument)

Example 68 with DocumentKey

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

the class MutationBatchResult method create.

/**
 * Creates a new MutationBatchResult for the given batch and results. There must be one result for
 * each mutation in the batch. This static factory caches a document=>version mapping (as
 * docVersions).
 */
public static MutationBatchResult create(MutationBatch batch, SnapshotVersion commitVersion, List<MutationResult> mutationResults, ByteString streamToken) {
    Assert.hardAssert(batch.getMutations().size() == mutationResults.size(), "Mutations sent %d must equal results received %d", batch.getMutations().size(), mutationResults.size());
    ImmutableSortedMap<DocumentKey, SnapshotVersion> docVersions = DocumentCollections.emptyVersionMap();
    List<Mutation> mutations = batch.getMutations();
    for (int i = 0; i < mutations.size(); i++) {
        SnapshotVersion version = mutationResults.get(i).getVersion();
        docVersions = docVersions.insert(mutations.get(i).getKey(), version);
    }
    return new MutationBatchResult(batch, commitVersion, mutationResults, streamToken, docVersions);
}
Also used : SnapshotVersion(com.google.firebase.firestore.model.SnapshotVersion) DocumentKey(com.google.firebase.firestore.model.DocumentKey)

Example 69 with DocumentKey

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

the class TestUtil method querySnapshot.

/**
 * A convenience method for creating a particular query snapshot for tests.
 *
 * @param path To be used in constructing the query.
 * @param oldDocs Provides the prior set of documents in the QuerySnapshot. Each entry maps to a
 *     document, with the key being the document id, and the value being the document contents.
 * @param docsToAdd Specifies data to be added into the query snapshot as of now. Each entry maps
 *     to a document, with the key being the document id, and the value being the document
 *     contents.
 * @param isFromCache Whether the query snapshot is cache result.
 * @return A query snapshot that consists of both sets of documents.
 */
public static QuerySnapshot querySnapshot(String path, Map<String, ObjectValue> oldDocs, Map<String, ObjectValue> docsToAdd, boolean hasPendingWrites, boolean isFromCache) {
    DocumentSet oldDocuments = docSet(Document.KEY_COMPARATOR);
    ImmutableSortedSet<DocumentKey> mutatedKeys = DocumentKey.emptyKeySet();
    for (Map.Entry<String, ObjectValue> pair : oldDocs.entrySet()) {
        String docKey = path + "/" + pair.getKey();
        MutableDocument doc = doc(docKey, 1L, pair.getValue());
        if (hasPendingWrites) {
            doc.setHasCommittedMutations();
            mutatedKeys = mutatedKeys.insert(key(docKey));
        }
        oldDocuments = oldDocuments.add(doc);
    }
    DocumentSet newDocuments = docSet(Document.KEY_COMPARATOR);
    List<DocumentViewChange> documentChanges = new ArrayList<>();
    for (Map.Entry<String, ObjectValue> pair : docsToAdd.entrySet()) {
        String docKey = path + "/" + pair.getKey();
        MutableDocument docToAdd = doc(docKey, 1L, pair.getValue());
        if (hasPendingWrites) {
            docToAdd.setHasCommittedMutations();
            mutatedKeys = mutatedKeys.insert(key(docKey));
        }
        newDocuments = newDocuments.add(docToAdd);
        documentChanges.add(DocumentViewChange.create(Type.ADDED, docToAdd));
    }
    ViewSnapshot viewSnapshot = new ViewSnapshot(com.google.firebase.firestore.testutil.TestUtil.query(path), newDocuments, oldDocuments, documentChanges, isFromCache, mutatedKeys, /* didSyncStateChange= */
    true, /* excludesMetadataChanges= */
    false);
    return new QuerySnapshot(query(path), viewSnapshot, FIRESTORE);
}
Also used : MutableDocument(com.google.firebase.firestore.model.MutableDocument) ArrayList(java.util.ArrayList) ViewSnapshot(com.google.firebase.firestore.core.ViewSnapshot) ObjectValue(com.google.firebase.firestore.model.ObjectValue) DocumentViewChange(com.google.firebase.firestore.core.DocumentViewChange) DocumentKey(com.google.firebase.firestore.model.DocumentKey) DocumentSet(com.google.firebase.firestore.model.DocumentSet) Map(java.util.Map)

Example 70 with DocumentKey

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

the class DocumentChangeTest method validatePositions.

private static void validatePositions(com.google.firebase.firestore.core.Query query, Collection<MutableDocument> initialDocsList, Collection<MutableDocument> addedList, Collection<MutableDocument> modifiedList, Collection<MutableDocument> removedList) {
    ImmutableSortedMap<DocumentKey, Document> initialDocs = docUpdates(initialDocsList.toArray(new MutableDocument[] {}));
    ImmutableSortedMap<DocumentKey, Document> updates = emptyDocumentMap();
    for (MutableDocument doc : addedList) {
        updates = updates.insert(doc.getKey(), doc);
    }
    for (MutableDocument doc : modifiedList) {
        updates = updates.insert(doc.getKey(), doc);
    }
    for (MutableDocument doc : removedList) {
        updates = updates.insert(doc.getKey(), doc);
    }
    View view = new View(query, DocumentKey.emptyKeySet());
    View.DocumentChanges initialChanges = view.computeDocChanges(initialDocs);
    TargetChange initialTargetChange = ackTarget(initialDocsList.toArray(new MutableDocument[] {}));
    ViewSnapshot initialSnapshot = view.applyChanges(initialChanges, initialTargetChange).getSnapshot();
    View.DocumentChanges updateChanges = view.computeDocChanges(updates);
    TargetChange updateTargetChange = targetChange(ByteString.EMPTY, true, addedList, modifiedList, removedList);
    ViewSnapshot updatedSnapshot = view.applyChanges(updateChanges, updateTargetChange).getSnapshot();
    if (updatedSnapshot == null) {
        // Nothing changed, no positions to verify
        return;
    }
    List<Document> expected = new ArrayList<>(updatedSnapshot.getDocuments().toList());
    List<Document> actual = new ArrayList<>(initialSnapshot.getDocuments().toList());
    FirebaseFirestore firestore = mock(FirebaseFirestore.class);
    List<DocumentChange> changes = DocumentChange.changesFromSnapshot(firestore, MetadataChanges.EXCLUDE, updatedSnapshot);
    for (DocumentChange change : changes) {
        if (change.getType() != Type.ADDED) {
            actual.remove(change.getOldIndex());
        }
        if (change.getType() != Type.REMOVED) {
            actual.add(change.getNewIndex(), change.getDocument().getDocument());
        }
    }
    assertEquals(expected, actual);
}
Also used : MutableDocument(com.google.firebase.firestore.model.MutableDocument) ArrayList(java.util.ArrayList) Document(com.google.firebase.firestore.model.Document) MutableDocument(com.google.firebase.firestore.model.MutableDocument) View(com.google.firebase.firestore.core.View) ViewSnapshot(com.google.firebase.firestore.core.ViewSnapshot) TargetChange(com.google.firebase.firestore.remote.TargetChange) DocumentKey(com.google.firebase.firestore.model.DocumentKey)

Aggregations

DocumentKey (com.google.firebase.firestore.model.DocumentKey)139 MutableDocument (com.google.firebase.firestore.model.MutableDocument)53 Test (org.junit.Test)36 HashMap (java.util.HashMap)34 ArrayList (java.util.ArrayList)24 Document (com.google.firebase.firestore.model.Document)20 Mutation (com.google.firebase.firestore.model.mutation.Mutation)18 Map (java.util.Map)18 SnapshotVersion (com.google.firebase.firestore.model.SnapshotVersion)16 ResourcePath (com.google.firebase.firestore.model.ResourcePath)13 MutationBatch (com.google.firebase.firestore.model.mutation.MutationBatch)11 ImmutableSortedMap (com.google.firebase.database.collection.ImmutableSortedMap)10 Overlay (com.google.firebase.firestore.model.mutation.Overlay)10 HashSet (java.util.HashSet)10 TestUtil.patchMutation (com.google.firebase.firestore.testutil.TestUtil.patchMutation)8 TestUtil.setMutation (com.google.firebase.firestore.testutil.TestUtil.setMutation)8 ByteString (com.google.protobuf.ByteString)7 Target (com.google.firebase.firestore.core.Target)6 ObjectValue (com.google.firebase.firestore.model.ObjectValue)6 TestUtil.deleteMutation (com.google.firebase.firestore.testutil.TestUtil.deleteMutation)6