• Start

API Reference

/

Core

SurrealTransaction

The transaction handle and helpers for atomic operations in the SurrealDB Kotlin SDK.

SurrealTransaction represents an in-progress transaction. It is itself a queryable, so the CRUD builders are available scoped to the transaction. Transactions are started with the extension functions on a session and require the WebSocket transport.

Source: surrealdb.kotlin

Import
import com.surrealdb.kotlin.beginTransaction
import com.surrealdb.kotlin.transaction

Runs the block against a new SurrealTransaction, committing it if the block returns normally and cancelling it if the block throws.

Method Syntax
session.transaction { /* ... */ }

Parameter

Type

Description

blocksuspend SurrealTransaction.() -> Unit

The operations to run inside the transaction.

Returns: Unit

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

Begins a transaction explicitly and returns a SurrealTransaction for manual commit or cancel.

Method Syntax
session.beginTransaction()

Returns: SurrealTransaction

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

Commits the transaction, persisting all its operations.

Method Syntax
tx.commit()

Returns: Unit

Cancels the transaction, discarding all its operations.

Method Syntax
tx.cancel()

Returns: Unit

Property

Type

Description

txnIdString

The transaction's identifier.

Was this page helpful?