Return CAS with N1QL update

Hi,

We have a requirement to create a new version of an existing record(couchbase document) everytime the record is updated.

The approach to be taken is:

  1. Update the doc and lock it using a JSON field(lock, in this example) and if the update is successful, return the document.
  2. If the record is retrieved and locked, the user can make further changes to the record and save it.
  3. On save we will match the CAS. and if it matches then the save is successful else not.

To achieve this we need to return the CAS value on the first operation itself, so as to be able to match it with the CAS during the third operation.

For the first operation we’re using N1ql query.
Questions:

  1. Is there a way to return CAS with N1ql query?
  2. If yes, then is there a difference in the CAS returned through N1ql and a sub-document API?

Request you to please help us out with this.

Sample Doc
Example:
Existing Document-

Record:1:OldTimeStamp
{
“id”:1,
“lock”:false,
“name”: “first name”,
“latestVersion”:true
}

On Step 1: updating the lock to “false”:
“Update BucketName record set lock = true where record.id=“1” AND record.lock = false AND record.latestVersion = true returning RAW record”

Record:1:OldTimeStamp
{
“id”:1,
“lock”:true,
“name”: “first name”,
“latestVersion”:true
}

On Step 3: Saving further changes to the record

Record:1:OldTimeStamp
{
“id”:1,
“lock”:false,
“name”: “first name”,
“latestVersion”:false
}

Record:1:NewTimeStamp
{
“id”:1,
“lock”:true,
“name”: “first name”,
“latestVersion”:true
}

In 7.0.0 RETURNING META().cas will give cas value

MB-43850

1 Like

Hi @vsr1 ,

Thanks for responding.

We’re using SDK .Net 2.7.8 with server 6.0.4.

Is there a way to do it here?

Hi @vsr1 ,

The solution you gave works with our version.

Thank You.

Just one more question, would there be a difference in the CAS value returned by N1QL and the one returned by SubDocument APIs.

If you use N1QL mutation statements want cas value you need 7.0.0

Hi @vsr1 ,

We’re using the following query :slight_smile:
" Update BucketName record set lock = true where record.id=“1” AND record.lock = false AND record.latestVersion = true returning Meta(record).cas, record"

This returns the older cas value(before update took place).

Is there a way to get the latest cas after the update is done?

You need CB 7.0.0 release or use SDK mutate document instead of N1QL o get cas value on update