transactions
A runner for transactional operations.
Samples
import com.couchbase.client.kotlin.Cluster
import com.couchbase.client.kotlin.Collection
import com.couchbase.client.kotlin.transactions.TransactionGetResult
import kotlin.random.Random
fun main() {
//sampleStart
// Assume two documents both contain integers.
// Subtract a value from the one document and add it to the other.
cluster.transactions.run {
// The SDK may execute this lambda multiple times
// if there are conflicts between transactions.
// All logic related to the transaction must happen
// inside this lambda.
// Inside the lambda, `this` is a `TransactionAttemptContext`
// with instance methods like `get`, `replace`, `insert`, `remove`,
// and `query` for interacting with documents in a transactional way.
// These are the only methods you should use to interact with documents
// inside the transaction lambda.
val source: TransactionGetResult = get(collection, sourceDocId)
val dest: TransactionGetResult = get(collection, destDocId)
val newSourceValue: Int = source.contentAs<Int>() - value
val newDestValue: Int = dest.contentAs<Int>() + value
replace(source, newSourceValue)
// Throwing any exception triggers a rollback and causes
// `transactions.run` to throw TransactionFailedException.
if (Random.nextBoolean()) throw RuntimeException("simulated error")
require(newSourceValue >= 0) { "transfer would result in negative source value" }
require(newDestValue >= 0) { "transfer would result in dest value overflow" }
replace(dest, newDestValue)
}
//sampleEnd
}