1. Transaction Module: transaction.xq

There is a helpful library you can use straight off the bat or alter to suit your needs called transaction.xq. This library allows you to perform multi-statement transactions in either update or read-only modes, where you can execute a set of operations in isolation, spread across multiple HTTP requests, then choose to either commit all the activity as a unit of work or rollback the lot as if none of it ever happened.

Import the module library into your main xqrs.xqy code and it's ready to go.

2. Register the RESTXQ module

import module namespace tx =
  "http://xmllondon.com/xquery/transaction" at
  "optional-libraries/transaction.xq";

This provides you with 4 RESTful services

URI Description
/transaction/start Start an Update transaction
/transaction/start-read-only Start a Read-Only transaction
/transaction/commit Commit the current transaction
/transaction/rollback Rollback the current transaction

When a client sends a request to either /transaction/start or /transaction/start-read-only the server will respond with 303 See Created Transaction, giving the client a cookie called XQRS-Session-ID. Providing the client sends this Cookie back on subsequent requests then each request will be executed within the context of that transaction.

When a client sends a request with the XQRS-Session-ID cookie, calling the following function, the new document only exists within the context of this transaction.

declare
  %rest:path("/my-stuff/{$uri}")
  %rest:update
  %rest:PUT("{$content}")
function insert($uri as xs:string, $content as document-node(element())) {
  xdmp:document-insert($uri, $content)
};

Once finished, the client can send a request to either the /transaction/commit or /transaction/rollback service along with the XQRS-Session-ID cookie.

3. Multiple concurrent transactions

As each XQRS-Session-ID is unique, there is nothing stopping you from running more than one transaction at the same time.

4. A transaction's lifespan

Transactions will timeout and rollback after 600 seconds.

TOP