• Start

Languages

/

Kotlin

/

Concepts

Transactions

Group operations into atomic transactions with the SurrealDB Kotlin SDK.

Transactions group multiple operations so they either all succeed or all fail together. The Kotlin SDK exposes transactions as extension functions on a session: a block form that commits or cancels automatically, and an explicit form for manual control.

MethodDescription
session.transaction { }Runs a block, committing or cancelling automatically
session.beginTransaction()Begins a transaction explicitly
tx.commit()Commits the transaction
tx.cancel()Cancels the transaction

The transaction { } builder runs your block against a SurrealTransaction, commits it if the block returns normally, and cancels it if the block throws. The transaction is itself a queryable, so all the CRUD builders are available scoped to it.

import com.surrealdb.kotlin.query.RecordId
import com.surrealdb.kotlin.transaction
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

client.transaction {
create(RecordId("person", "tx"))
.content(buildJsonObject { put("name", "Tx") })
.await()

update(RecordId("counter", "1"))
.content(buildJsonObject { put("hits", 2) })
.await()
}

For finer control, begin a transaction with .beginTransaction() and commit or cancel it yourself.

import com.surrealdb.kotlin.query.Table
import com.surrealdb.kotlin.beginTransaction
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

val tx = client.beginTransaction()
try {
tx.create(Table("person"))
.content(buildJsonObject { put("name", "Ada") })
.await()
tx.commit()
} catch (cause: Throwable) {
tx.cancel()
throw cause
}

Was this page helpful?