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.
Transactions require a stateful connection and are only available over the WebSocket transport. Check support with client.supports(SurrealFeature.Transactions).
API references
Method | Description |
|---|---|
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 |
Block form
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()
}Explicit form
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
}Learn more
Transaction reference for the full API
Multiple sessions — transactions run within a session
SurrealQL transactions for transaction semantics