Search code examples
firebasegoogle-cloud-firestoretransactionsfirebase-storagefile-storage

Is it possible to run Transactions and batched writes for Firestore and Firebase-Storage simultaneously?


Use-Case: I have to write in some document_1 update in document_2 and delete document_3 and delete file_4 from file_storage using single transaction using Transactions and batched writes. Is it possible? If possible how?

Note: All four async task should be success when complete OR all four task should be failed. If the case is read and write only this Transactions and batched writes documentation can help. But in our case there is file read - upload - delete task too.

Future<void> _runTransaction() async {
firestore.runTransaction((Transaction transaction) async {
  final allDocs = await firestore.collection("messages").getDocuments();
  final toBeRetrieved =
      allDocs.documents.sublist(allDocs.documents.length ~/ 2);
  final toBeDeleted =
      allDocs.documents.sublist(0, allDocs.documents.length ~/ 2);
  await Future.forEach(toBeDeleted, (DocumentSnapshot snapshot) async {
    await transaction.delete(snapshot.reference);
  });

  await Future.forEach(toBeRetrieved, (DocumentSnapshot snapshot) async {
    await transaction.update(snapshot.reference, {
      "message": "Updated from Transaction",
      "created_at": FieldValue.serverTimestamp()
    });
  });
});

await Future.forEach(List.generate(2, (index) => index), (item) async {
  await firestore.runTransaction((Transaction transaction) async {
    await Future.forEach(List.generate(10, (index) => index), (item) async {
      await transaction.set(firestore.collection("messages").document(), {
        "message": "Created from Transaction $item",
        "created_at": FieldValue.serverTimestamp()
      });
    });
  });
});

}


Solution

  • At the time of writing, you cannot include write operations to Firestore with write operations to Cloud Storage in one atomic operation.

    As you have mentioned, you can use a batched write for your write/update/delete operations in Firestore and this will be atomic, but you cannot include the write to Storage.


    You could build your own mechanism that regularly checks that for each file in Cloud Storage there is the corresponding configuration in Firestore (docs are correctly updated, deleted, etc...) and vice versa. Just a suggestion of a (very) hacky workaround...