Using transactional batch in cosmos, is it possible to query a partition within a collection (Select * from partition where openOrder=1
) and then IF the query returns that there are no open orders, add an item to the collection.
Or you could have the write first, and then have the conditional read (Select * from partition where openOrder=1 and id={unique GUID just written}
) and then if the 2nd read fails, the write would be reversed (?).
Would want this to be done in one atomic operation because I don't want to think there are no open orders and then another process writes an open order before this process can.
If not, is it possible to do this a different way?
**Edit 3:30 PM PT 9/16 with attempted solution that wrote a document when I tested it **
function checkOpenOrder(inputDocString, query){
console.log("Stored Procedure Starting")
var context = getContext();
var container = context.getCollection();
var containerLink = container.getSelfLink();
var response = context.getResponse();
var isAccepted = container.queryDocuments(
container.getSelfLink(),
query,
function (err, items, options) {
if (err) throw err;
// Query would be fed in such that if there is no open order, no items would return in the collection
if (items.length == 0){
var docCreated = container.createDocument(containerLink, inputDocString,
function (err2, itemWritten) {
if (err2) throw err2;
// else was successfully able to write document?
response.setBody("Wrote document");
});
}
else {
response.setBody("Order currently open");
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.')
}
Edit: Final question 9/17 Would I want to set max degree of parallelism to 1 to ensure that the stored procedure cannot run 2x in the same partition at the same time? (which could create a race condition if it sees there's no open order -> creates a document and then we have 2 open orders). I think that I want cross partition query disabled (plus I will not need it).