Single Node CouchDB, Multi Doc Transaction

473 views Asked by At

Assuming there is a validate_doc_update function, in the design document, defined as:

{
   "_id": "_design/ddoc",
   "_rev": "12-133b5dad579f872884a9ccd6d4be5ee9",
   "language": "javascript",
   "validate_doc_update": "function(newDoc, oldDoc, userCtx) {
        if (oldDoc._rev != newDoc._rev) { throw('FAILED') }
   }"
}

If we perform a bulk update (_bulk_docs); is it transnational for more than one document?

Note: I've found this answer and have read the documents and have run some test code. And it seems it's a perfect way to perform transactions on CouchDB! But since I've not seen it on other places (and wondered why?); wanted to make sure that, this is not a mistake.

2

There are 2 answers

0
Jan Lehnardt On BEST ANSWER

CouchDB dev here.

This is not transactional, and it’s by design, even on a single node.

The reason is that we don’t want to have any APIs in CouchDB that break when you go from a single node installation to a cluster installation.

In a cluster, it is much harder to guarantee a multi-doc transaction, so CouchDB doesn’t even attempt it.

0
Bernhard Gschwantner On

I'd like to add that you can often store the complete transaction into a single document and then take views to your advantage to show the results.

For example, for storing a cash transfer, instead of storing two documents describing the deposit and the withdrawal, store both in a "transfer" type document, and then create a view returning the balances of each account.

Or to take the example in the question you referred to: If you want to ensure there is only one king in the database at a time, just use a document with the _id = 'king' and store all the information about the king there. If the king changes, just change the actual data of the king in that document. You would get a conflict if two clients tried to change the king at the same time. Btw this would also work great if you used multiple nodes or multiple replicas, for example for offline-first clients via PouchDB. You'd have to consider resolving conflicts eventually, but by design you'd never run into two kings.

So: depending on your needs, model your documents accordingly. If you need transactions, store each transaction as a single document.