Reputation: 11
I want to implement optimistic locking based on duplicate document URIs in my application using MarkLogic as datastore.
I read the xdmp:document-insert()
documentation and found that MarkLogic does not throw an exception on inserting another page with same URI, but instead updates the content of page, page permission, and properties with that of the new page. But is there any way by which we can achieve this in MarkLogic?
Upvotes: 1
Views: 505
Reputation: 201
You may also use the fn:doc-available() function. Returns Boolean true if document exists otherwise returns Boolean false.
Find details here - https://docs.marklogic.com/fn:doc-available
Upvotes: 0
Reputation: 392
You will want to test for the existence of the doc using:
xdmp:exists(fn:doc($uri))
That will test for existence of a doc at the URI without actually loading the doc. You can then determine, how you want to handle the situation.
Upvotes: 1
Reputation: 7840
Good answers, but I think you need to back up and ask what your application goals are, rather than presuming that you need to implement optimistic locking. MarkLogic Server does optimistic locking internally, and so perhaps you don't need to worry about it. Read http://docs.marklogic.com/5.0doc/docapp.xqy#display.xqy?fname=http%3a//pubs/5.0doc/xml/dev_guide/transactions.xml for more background on MarkLogic and transactions.
When you do need to check for document existence in an update, use fn:doc
- not cts:uri-match
or xdmp:exists
. Those functions are great for read-only queries because they do not load documents into memory. That is fine for read-only queries. But if you need to check document existence in an update, then you need to take a read lock on it to ensure consistency. Otherwise you will have code that appears to work, but has potential for race conditions. To ensure that you take a read lock, use fn:exists(fn:doc($uri))
or call fn:doc($uri)
in an effective boolean context.
http://docs.marklogic.com/5.0doc/docapp.xqy#display.xqy?fname=http://pubs/5.0doc/apidoc/UpdateBuiltins.xml&category=UpdateBuiltins&function=xdmp:lock-for-update might also be of interest. The xdmp:lock-for-update
function bypasses the default, optimistic behavior and explicitly takes a lock on a URI. If you do this as early as possible in your update code, you have pessimistic locking. In situations where you know that there will be heavy contention on a URI, that approach can deliver better performance.
Upvotes: 3
Reputation: 20414
Test the existance of the doc before you do the insert. I think cts:uri-match
is one of the fastest ways to do so. If it already exists, you could throw an exception of your own using fn:error()
.
Not sure what this got to do with optimistic locking though..
Upvotes: 2