# SurrealDB documentation - Kotlin SDK

> Quickstart, concepts and API reference. This is one of the bundles the SurrealDB documentation is split into. The page index at https://surrealdb.com/docs/llms.txt lists every bundle, and https://surrealdb.com/docs/llms-full.txt holds every page. Each page starts with a "Source:" line naming its canonical URL, and every page is also available individually by appending `.md` to its URL. In code examples, a fenced block whose title contains "output" holds the result of the block above it rather than runnable code, and a qualifier such as "Example output" or "Possible output" means the value shown is one of several possible ones. Inside a block, a "//-" comment marks a value the statement above it returned, while "--" is an ordinary comment.

---

Source: https://surrealdb.com/docs/reference/kotlin

# Kotlin SDK

The official SurrealDB SDK for Kotlin. A coroutine-based, Kotlin Multiplatform client for querying a remote instance.

The SurrealDB SDK for Kotlin lets you connect to [SurrealDB](/docs) from any Kotlin application. It is a [Kotlin Multiplatform](https://kotlinlang.org/docs/multiplatform.html) library targeting the JVM, Android, and iOS, with a coroutine-based, `suspend`-friendly API. The SDK connects to remote instances over WebSocket or HTTP and provides methods for querying with [SurrealQL](/docs/reference/query-language.md), managing data, [authentication](/docs/learn/security/authentication/users.md), live queries, transactions, and multiple sessions. Its design closely mirrors the [JavaScript SDK](/docs/languages/javascript.md).

> [!NOTE]
> The Kotlin SDK is currently in early development. The latest version is `0.1.0-SNAPSHOT`, and it is not yet published to Maven Central. The coordinates and APIs documented here are provisional and may change before the first stable release.

## Getting started

- [Installation](/docs/reference/kotlin/installation.md) - Install the SDK and add it to your project.

- [Getting started guide](/docs/languages/kotlin.md) - Connect to SurrealDB and run your first queries.

## Learn

- [Concepts](/docs/reference/kotlin/concepts/connecting-to-surrealdb.md) - Guides for connecting, authenticating, querying, and working with data.

- [API Reference](/docs/reference/kotlin/api/core/surreal-client.md) - Complete reference for the SDK's methods, types, and errors.

## Contributing

To contribute to the SDK code, submit an Issue or Pull Request in the [surrealdb.kotlin](https://github.com/surrealdb/surrealdb.kotlin) repository. To contribute to this documentation, submit an Issue or Pull Request in the [docs.surrealdb.com](https://github.com/surrealdb/docs.surrealdb.com) repository.

## Sources

- [GitHub repository](https://github.com/surrealdb/surrealdb.kotlin)

---

Source: https://surrealdb.com/docs/reference/kotlin/api/core/client-config

# SurrealClientConfig

Configuration options for the SurrealDB Kotlin client, including reconnection and authentication.

`SurrealClientConfig` configures a [`SurrealClient`](/docs/reference/kotlin/api/core/surreal-client.md). The only required field is `url`; everything else has a sensible default.

**Source:** [surrealdb.kotlin](https://github.com/surrealdb/surrealdb.kotlin)

```kotlin title="Import"
import com.surrealdb.kotlin.SurrealClientConfig
```

---

## Fields

<table>
    <thead>
        <tr><th>Field</th><th>Type</th><th>Default</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr>
            <td><code>url</code> _(required)_</td>
            <td><code>String</code></td>
            <td>-</td>
            <td>The connection URL. The scheme (<code>ws</code>/<code>wss</code>/<code>http</code>/<code>https</code>) selects the transport.</td>
        </tr>
        <tr>
            <td id="json"><code>json</code></td>
            <td><code>Json</code></td>
            <td>lenient</td>
            <td>The <code>kotlinx.serialization</code> instance used for encoding and decoding.</td>
        </tr>
        <tr>
            <td><code>autoConnect</code></td>
            <td><code>Boolean</code></td>
            <td><code>true</code></td>
            <td>Connect lazily on the first request.</td>
        </tr>
        <tr>
            <td><code>autoAuthenticate</code></td>
            <td><code>Boolean</code></td>
            <td><code>false</code></td>
            <td>Authenticate automatically using <code>credentialProvider</code> on connect and reconnect.</td>
        </tr>
        <tr>
            <td><code>credentialProvider</code></td>
            <td><code>(suspend () -&gt; SurrealAuthInput?)?</code></td>
            <td><code>null</code></td>
            <td>Supplies credentials for automatic authentication and token renewal.</td>
        </tr>
        <tr>
            <td><code>requestTimeoutMillis</code></td>
            <td><code>Long</code></td>
            <td><code>30_000</code></td>
            <td>Per-request timeout in milliseconds.</td>
        </tr>
        <tr>
            <td><code>reconnect</code></td>
            <td><code>ReconnectConfig</code></td>
            <td><code>ReconnectConfig()</code></td>
            <td>WebSocket reconnection behaviour.</td>
        </tr>
        <tr>
            <td><code>tokenRenewalLeadMillis</code></td>
            <td><code>Long</code></td>
            <td><code>60_000</code></td>
            <td>How long before token expiry to renew, in milliseconds.</td>
        </tr>
        <tr>
            <td><code>httpClientFactory</code></td>
            <td><code>((SurrealClientConfig) -&gt; HttpClient)?</code></td>
            <td><code>null</code></td>
            <td>Supplies a custom Ktor <code>HttpClient</code>.</td>
        </tr>
    </tbody>
</table>

```kotlin title="Example"
import com.surrealdb.kotlin.SurrealAuthInput
import com.surrealdb.kotlin.SurrealClientConfig
import com.surrealdb.kotlin.engine.ReconnectConfig
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

val config = SurrealClientConfig(
    url = "wss://example.com",
    requestTimeoutMillis = 30_000,
    autoAuthenticate = true,
    tokenRenewalLeadMillis = 60_000,
    reconnect = ReconnectConfig(enabled = true, multiplier = 1.5),
    credentialProvider = {
        SurrealAuthInput.SignIn(buildJsonObject {
            put("user", "root")
            put("pass", "root")
        })
    },
)
```

---

## `ReconnectConfig` {#reconnect-config}

Controls exponential-backoff reconnection on the WebSocket transport.

```kotlin title="Import"
import com.surrealdb.kotlin.engine.ReconnectConfig
```

<table>
    <thead>
        <tr><th>Field</th><th>Type</th><th>Default</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr><td><code>enabled</code></td><td><code>Boolean</code></td><td><code>true</code></td><td>Whether reconnection is attempted.</td></tr>
        <tr><td><code>initialDelayMillis</code></td><td><code>Long</code></td><td><code>250</code></td><td>Delay before the first retry.</td></tr>
        <tr><td><code>maxDelayMillis</code></td><td><code>Long</code></td><td><code>30_000</code></td><td>Maximum delay between retries.</td></tr>
        <tr><td><code>multiplier</code></td><td><code>Double</code></td><td><code>1.5</code></td><td>Backoff multiplier applied each attempt.</td></tr>
        <tr><td><code>maxAttempts</code></td><td><code>Int?</code></td><td><code>null</code></td><td>Maximum attempts; <code>null</code> retries indefinitely.</td></tr>
    </tbody>
</table>

---

## `SurrealAuthInput` {#surreal-auth-input}

A sealed interface describing how `credentialProvider` should authenticate.

```kotlin title="Import"
import com.surrealdb.kotlin.SurrealAuthInput
```

<table>
    <thead>
        <tr><th>Variant</th><th>Payload</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr><td><code>SurrealAuthInput.SignIn</code></td><td><code>params: JsonObject</code></td><td>Sign in with credentials.</td></tr>
        <tr><td><code>SurrealAuthInput.Token</code></td><td><code>token: String</code></td><td>Authenticate with an existing token.</td></tr>
    </tbody>
</table>

## Learn more

- [SurrealClient API reference](/docs/reference/kotlin/api/core/surreal-client.md)
- [Connecting to SurrealDB](/docs/reference/kotlin/concepts/connecting-to-surrealdb.md)
- [Authentication](/docs/reference/kotlin/concepts/authentication.md)

---

Source: https://surrealdb.com/docs/reference/kotlin/api/core/live-subscription

# LiveQuerySubscription

The subscription handle returned by live queries in the SurrealDB Kotlin SDK.

`LiveQuerySubscription` is returned by [`.live()`](/docs/reference/kotlin/api/core/surreal-client.md#live). It exposes a coroutine [`Flow`](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/) of notifications and a method to stop the subscription. See [Live queries](/docs/reference/kotlin/concepts/live-queries.md) for the concept.

**Source:** [surrealdb.kotlin](https://github.com/surrealdb/surrealdb.kotlin)

```kotlin title="Import"
import com.surrealdb.kotlin.live.LiveQuerySubscription
```

---

## Members

### `id` {#id}

The server-assigned live query ID.

**Type:** `String`

### `events` {#events}

A flow of [`SurrealLiveNotification`](#notification) events for this subscription.

**Type:** `Flow<SurrealLiveNotification>`

```kotlin title="Example"
subscription.events.collect { event ->
    println("${event.action}: ${event.result}")
}
```

### `.cancel()` {#cancel}

Stops the subscription and kills the underlying live query on the server.

```kotlin title="Method Syntax"
subscription.cancel()
```

**Returns:** `Unit`

---

## `SurrealLiveNotification` {#notification}

The payload emitted on the [`events`](#events) flow.

```kotlin title="Import"
import com.surrealdb.kotlin.model.SurrealLiveNotification
```

<table>
    <thead>
        <tr><th>Field</th><th>Type</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr><td><code>action</code></td><td><code>String</code></td><td>The change kind: <code>"CREATE"</code>, <code>"UPDATE"</code>, or <code>"DELETE"</code>.</td></tr>
        <tr><td><code>liveQueryId</code></td><td><code>String</code></td><td>The ID of the originating live query.</td></tr>
        <tr><td><code>result</code></td><td><code>JsonElement</code></td><td>The changed record or diff.</td></tr>
    </tbody>
</table>

## Learn more

- [Live queries](/docs/reference/kotlin/concepts/live-queries.md)
- [SurrealClient API reference](/docs/reference/kotlin/api/core/surreal-client.md) for `.live()` and `.kill()`

---

Source: https://surrealdb.com/docs/reference/kotlin/api/core/query-builder

# Query builders

The fluent query builders, expression helpers, and surql DSL of the SurrealDB Kotlin SDK.

The CRUD methods on [`SurrealClient`](/docs/reference/kotlin/api/core/surreal-client.md) return fluent builders that compile to [SurrealQL](/docs/reference/query-language.md). Each builder is refined with chainable methods and terminated with [`await()`](#await) (raw [`JsonElement`](/docs/reference/kotlin/api/values/value.md)) or the typed [`awaitAs<T>()`](#await-as) extension.

**Source:** [surrealdb.kotlin](https://github.com/surrealdb/surrealdb.kotlin)

```kotlin title="Import"
import com.surrealdb.kotlin.query.awaitAs
import com.surrealdb.kotlin.query.field
import com.surrealdb.kotlin.query.gte
```

---

## Terminal methods

### `.await()` {#await}

Executes the builder and returns the unwrapped result of the first statement as a [`JsonElement`](/docs/reference/kotlin/api/values/value.md).

```kotlin title="Method Syntax"
builder.await()
```

**Returns:** `JsonElement`

### `.awaitRaw()` {#await-raw}

Executes the builder and returns the raw `[{ status, result, time, type }]` response envelope.

```kotlin title="Method Syntax"
builder.awaitRaw()
```

**Returns:** `JsonElement`

### `.awaitAs<T>()` {#await-as}

An inline extension that executes the builder and decodes the result into `T` using [`kotlinx.serialization`](/docs/reference/kotlin/concepts/serialization.md). Available on every builder.

```kotlin title="Method Syntax"
builder.awaitAs<T>()
```

**Returns:** `T`

```kotlin title="Example"
val people: List<Person> = client.select(Table("person")).awaitAs()
```

### `.compile()` {#compile}

Compiles the builder to a `BoundQuery` without executing it - useful for inspection or composing with [`.query()`](/docs/reference/kotlin/api/core/surreal-client.md#query).

```kotlin title="Method Syntax"
builder.compile()
```

**Returns:** `BoundQuery`

---

## `SelectQuery` {#select-query}

Returned by [`.select(what)`](/docs/reference/kotlin/api/core/surreal-client.md#select).

<table>
    <thead>
        <tr><th>Method</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr><td id="fields"><code>.fields(vararg names)</code></td><td>Selects specific fields.</td></tr>
        <tr><td><code>.value(field)</code></td><td>Selects a single field's value.</td></tr>
        <tr><td id="where"><code>.where(expr)</code></td><td>Filters with an <a href="#expressions">expression</a>.</td></tr>
        <tr><td id="start"><code>.start(n)</code></td><td>Skips the first <code>n</code> records.</td></tr>
        <tr><td id="limit"><code>.limit(n)</code></td><td>Limits the number of records.</td></tr>
        <tr><td id="fetch"><code>.fetch(vararg fields)</code></td><td>Fetches related records.</td></tr>
        <tr><td><code>.timeout(seconds)</code></td><td>Sets a query timeout.</td></tr>
        <tr><td><code>.version(literal)</code></td><td>Reads at a specific version.</td></tr>
    </tbody>
</table>

```kotlin title="Example"
val adults: List<Person> = client
    .select(Table("person"))
    .where(field("age") gte 18)
    .limit(50)
    .awaitAs()
```

## Content builders

[`CreateQuery`](/docs/reference/kotlin/api/core/surreal-client.md#create), [`UpdateQuery`](/docs/reference/kotlin/api/core/surreal-client.md#update), [`UpsertQuery`](/docs/reference/kotlin/api/core/surreal-client.md#upsert), and [`RelateQuery`](/docs/reference/kotlin/api/core/surreal-client.md#relate) accept content and a return mode.

<table>
    <thead>
        <tr><th>Method</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr><td><code>.content(data)</code></td><td>Sets the record content (a <code>JsonElement</code>).</td></tr>
        <tr><td><code>.where(expr)</code></td><td>Filters affected records (update, upsert, merge, patch, delete).</td></tr>
        <tr><td id="return-mode"><code>.returnMode(mode)</code></td><td>Controls the returned payload (see <a href="#return-mode-type">ReturnMode</a>).</td></tr>
    </tbody>
</table>

## `ReturnMode` {#return-mode-type}

```kotlin title="Import"
import com.surrealdb.kotlin.query.ReturnMode
```

<table>
    <thead>
        <tr><th>Value</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr><td><code>ReturnMode.None</code></td><td>Returns nothing.</td></tr>
        <tr><td><code>ReturnMode.Before</code></td><td>Returns records as they were before the change.</td></tr>
        <tr><td><code>ReturnMode.After</code></td><td>Returns records after the change.</td></tr>
        <tr><td><code>ReturnMode.Diff</code></td><td>Returns a JSON Patch diff.</td></tr>
        <tr><td><code>ReturnMode.Fields(names)</code></td><td>Returns only the named fields.</td></tr>
    </tbody>
</table>

## `RunQuery` {#run-query}

Returned by [`.run(function)`](/docs/reference/kotlin/api/core/surreal-client.md#run).

<table>
    <thead>
        <tr><th>Method</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr><td><code>.args(vararg args)</code></td><td>Sets the function arguments.</td></tr>
        <tr><td><code>.version(version)</code></td><td>Selects a function version.</td></tr>
    </tbody>
</table>

---

## Expression helpers {#expressions}

Build `WHERE` expressions with the helper functions and infix operators from `com.surrealdb.kotlin.query`.

```kotlin title="Import"
import com.surrealdb.kotlin.query.field
import com.surrealdb.kotlin.query.value
import com.surrealdb.kotlin.query.gte
import com.surrealdb.kotlin.query.and
```

<table>
    <thead>
        <tr><th>Helper</th><th>SurrealQL</th></tr>
    </thead>
    <tbody>
        <tr><td><code>field(name)</code></td><td>A validated field reference.</td></tr>
        <tr><td><code>value(any)</code></td><td>A literal value.</td></tr>
        <tr><td><code>raw(boundQuery)</code></td><td>A raw fragment.</td></tr>
        <tr><td><code>a eq b</code></td><td><code>=</code></td></tr>
        <tr><td><code>a neq b</code></td><td><code>!=</code></td></tr>
        <tr><td><code>a lt b</code></td><td><code>&lt;</code></td></tr>
        <tr><td><code>a lte b</code></td><td><code>&lt;=</code></td></tr>
        <tr><td><code>a gt b</code></td><td><code>&gt;</code></td></tr>
        <tr><td><code>a gte b</code></td><td><code>&gt;=</code></td></tr>
        <tr><td><code>a contains b</code></td><td><code>CONTAINS</code></td></tr>
        <tr><td><code>a inside b</code></td><td><code>IN</code></td></tr>
        <tr><td><code>a and b</code></td><td><code>AND</code></td></tr>
        <tr><td><code>a or b</code></td><td><code>OR</code></td></tr>
        <tr><td><code>not(expr)</code></td><td><code>!</code></td></tr>
    </tbody>
</table>

> [!NOTE]
> Inequality is `neq` (not `ne`) and membership is `inside` (not `in`, which is a reserved Kotlin keyword).

```kotlin title="Example"
import com.surrealdb.kotlin.query.field
import com.surrealdb.kotlin.query.gte
import com.surrealdb.kotlin.query.eq
import com.surrealdb.kotlin.query.and

val expr = (field("age") gte 18) and (field("active") eq true)
val results = client.select(Table("person")).where(expr).awaitAs<List<Person>>()
```

---

## `surql` DSL {#surql}

The `surql` helpers build a parameterised `BoundQuery` with automatic, injection-safe binding of values and record identifiers.

```kotlin title="Import"
import com.surrealdb.kotlin.query.surql
```

```kotlin title="Example"
// Vararg bindings
val a = surql("SELECT * FROM person WHERE age > \$min", "min" to 25)

// Builder block
val b = surql {
    +"SELECT * FROM person WHERE age > "
    param("min", 25)
}

val result = client.query(a)
```

## Learn more

- [SurrealClient API reference](/docs/reference/kotlin/api/core/surreal-client.md) for the CRUD methods
- [Data manipulation](/docs/reference/kotlin/concepts/data-manipulation.md) for the concepts
- [Serialisation](/docs/reference/kotlin/concepts/serialization.md) for `awaitAs`

---

Source: https://surrealdb.com/docs/reference/kotlin/api/core/session

# SurrealSession

The SurrealSession class exposes querying and authentication with isolated per-session state.

`SurrealSession` is the base class of [`SurrealClient`](/docs/reference/kotlin/api/core/surreal-client.md) and the type returned by [`.newSession()`](/docs/reference/kotlin/api/core/surreal-client.md#new-session). It exposes the full querying, authentication, and CRUD API with state - authentication, namespace, database, and parameters - isolated to that session. See [Multiple sessions](/docs/reference/kotlin/concepts/multiple-sessions.md) for the concept.

**Source:** [surrealdb.kotlin](https://github.com/surrealdb/surrealdb.kotlin)

---

## Shared API

Because [`SurrealClient`](/docs/reference/kotlin/api/core/surreal-client.md) extends `SurrealSession`, every session - root or child - provides the same methods documented on the client:

- Connection: [`.use()`](/docs/reference/kotlin/api/core/surreal-client.md#use), [`.ping()`](/docs/reference/kotlin/api/core/surreal-client.md#ping), [`.version()`](/docs/reference/kotlin/api/core/surreal-client.md#version)
- Authentication: [`.signin()`](/docs/reference/kotlin/api/core/surreal-client.md#signin), [`.signup()`](/docs/reference/kotlin/api/core/surreal-client.md#signup), [`.authenticate()`](/docs/reference/kotlin/api/core/surreal-client.md#authenticate), [`.auth()`](/docs/reference/kotlin/api/core/surreal-client.md#auth), [`.invalidate()`](/docs/reference/kotlin/api/core/surreal-client.md#invalidate), [`.reset()`](/docs/reference/kotlin/api/core/surreal-client.md#reset)
- Queries: [`.query()`](/docs/reference/kotlin/api/core/surreal-client.md#query), [`.queryAs<T>()`](/docs/reference/kotlin/api/core/surreal-client.md#query-as), [`.let()`](/docs/reference/kotlin/api/core/surreal-client.md#let), [`.unset()`](/docs/reference/kotlin/api/core/surreal-client.md#unset)
- CRUD builders: [`.select()`](/docs/reference/kotlin/api/core/surreal-client.md#select), [`.create()`](/docs/reference/kotlin/api/core/surreal-client.md#create), [`.update()`](/docs/reference/kotlin/api/core/surreal-client.md#update), [`.upsert()`](/docs/reference/kotlin/api/core/surreal-client.md#upsert), [`.merge()`](/docs/reference/kotlin/api/core/surreal-client.md#merge), [`.patch()`](/docs/reference/kotlin/api/core/surreal-client.md#patch), [`.delete()`](/docs/reference/kotlin/api/core/surreal-client.md#delete), [`.relate()`](/docs/reference/kotlin/api/core/surreal-client.md#relate), [`.insert()`](/docs/reference/kotlin/api/core/surreal-client.md#insert)
- Live queries: [`.live()`](/docs/reference/kotlin/api/core/surreal-client.md#live), [`.kill()`](/docs/reference/kotlin/api/core/surreal-client.md#kill)

## Session state accessors

<table>
    <thead>
        <tr><th>Method</th><th>Type</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr><td><code>.namespace()</code></td><td><code>String?</code></td><td>The session's current namespace.</td></tr>
        <tr><td><code>.database()</code></td><td><code>String?</code></td><td>The session's current database.</td></tr>
        <tr><td><code>.accessToken()</code></td><td><code>String?</code></td><td>The session's current access token, if authenticated.</td></tr>
    </tbody>
</table>

## Creating and closing sessions

```kotlin title="Example"
val session = client.newSession()
session.signin(buildJsonObject { put("user", "a"); put("pass", "a") })
session.use("acme", "main")

// ... use the session ...

client.closeSession(session)
```

## Transactions

Transactions are started on a session via the [`transaction { }`](/docs/reference/kotlin/api/core/transaction.md#transaction-block) and [`beginTransaction()`](/docs/reference/kotlin/api/core/transaction.md#begin-transaction) extension functions. See the [Transaction reference](/docs/reference/kotlin/api/core/transaction.md).

## Learn more

- [SurrealClient API reference](/docs/reference/kotlin/api/core/surreal-client.md)
- [Multiple sessions](/docs/reference/kotlin/concepts/multiple-sessions.md)
- [Transaction reference](/docs/reference/kotlin/api/core/transaction.md)

---

Source: https://surrealdb.com/docs/reference/kotlin/api/core/surreal-client

# SurrealClient

The SurrealClient class is the main entry point for connecting to and interacting with a SurrealDB instance from Kotlin.

The `SurrealClient` class is the main entry point for the Kotlin SDK. It connects to a SurrealDB instance, authenticates, queries, and manages data. It extends [`SurrealSession`](/docs/reference/kotlin/api/core/session.md) and implements `AutoCloseable`. Almost every networked method is a `suspend` function and has a `...Result` companion that returns a [`Result`](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-result/) instead of throwing.

**Source:** [surrealdb.kotlin](https://github.com/surrealdb/surrealdb.kotlin)

```kotlin title="Import"
import com.surrealdb.kotlin.SurrealClient
import com.surrealdb.kotlin.SurrealClientConfig
```

---

## Connection methods

### `SurrealClient(config)` {#constructor}

Creates a new client from a [`SurrealClientConfig`](/docs/reference/kotlin/api/core/client-config.md). With `autoConnect = true` (the default) the client connects lazily on the first request.

```kotlin title="Method Syntax"
SurrealClient(config)
```

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>config</code> _(required)_</td>
            <td><code>SurrealClientConfig</code></td>
            <td>The client configuration, including the connection <code>url</code>.</td>
        </tr>
    </tbody>
</table>

**Returns:** `SurrealClient`

```kotlin title="Example"
val client = SurrealClient(SurrealClientConfig(url = "ws://localhost:8000"))
```

### `.connect()` {#connect}

Establishes the connection explicitly. Rarely needed when `autoConnect` is enabled.

```kotlin title="Method Syntax"
client.connect()
```

**Returns:** `Unit`

```kotlin title="Example"
client.connect()
```

### `.close()` {#close}

Closes the active connection and releases all associated resources.

```kotlin title="Method Syntax"
client.close()
```

**Returns:** `Unit`

```kotlin title="Example"
client.close()
```

### `.use(namespace, database)` {#use}

Selects the namespace and database for subsequent operations.

```kotlin title="Method Syntax"
client.use(namespace, database)
```

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>namespace</code> _(required)_</td>
            <td><code>String</code></td>
            <td>The namespace to select.</td>
        </tr>
        <tr>
            <td><code>database</code> _(required)_</td>
            <td><code>String</code></td>
            <td>The database to select.</td>
        </tr>
    </tbody>
</table>

**Returns:** `JsonElement`

```kotlin title="Example"
client.use("surrealdb", "docs")
```

### `.ping()` {#ping}

Pings the server to verify connectivity.

```kotlin title="Method Syntax"
client.ping()
```

**Returns:** `JsonElement`

### `.version()` {#version}

Returns the version of the connected SurrealDB server.

```kotlin title="Method Syntax"
client.version()
```

**Returns:** `JsonElement`

```kotlin title="Example"
val version = client.version()
```

### `.supports(feature)` {#supports}

Returns whether the current transport supports the given [`SurrealFeature`](/docs/reference/kotlin/api/features.md#feature).

```kotlin title="Method Syntax"
client.supports(feature)
```

<table>
    <thead>
        <tr>
            <th>Parameter</th>
            <th>Type</th>
            <th>Description</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><code>feature</code> _(required)_</td>
            <td><code>SurrealFeature</code></td>
            <td>The feature to check.</td>
        </tr>
    </tbody>
</table>

**Returns:** `Boolean`

```kotlin title="Example"
if (client.supports(SurrealFeature.LiveQueries)) { /* ... */ }
```

---

## Authentication methods

### `.signup(params)` {#signup}

Signs up against a [record access](/docs/reference/query-language/statements/define/access/record.md) method and returns a token.

```kotlin title="Method Syntax"
client.signup(params)
```

<table>
    <thead>
        <tr><th>Parameter</th><th>Type</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr>
            <td><code>params</code> _(required)_</td>
            <td><code>JsonObject</code></td>
            <td>The sign-up parameters (namespace, database, access, and any record variables).</td>
        </tr>
    </tbody>
</table>

**Returns:** `JsonElement`

### `.signin(params)` {#signin}

Signs in with the given credentials and returns a token.

```kotlin title="Method Syntax"
client.signin(params)
```

<table>
    <thead>
        <tr><th>Parameter</th><th>Type</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr>
            <td><code>params</code> _(required)_</td>
            <td><code>JsonObject</code></td>
            <td>The sign-in credentials.</td>
        </tr>
    </tbody>
</table>

**Returns:** `JsonElement`

```kotlin title="Example"
client.signin(buildJsonObject {
    put("user", "root")
    put("pass", "root")
})
```

### `.authenticate(token)` {#authenticate}

Authenticates the session with an existing token.

```kotlin title="Method Syntax"
client.authenticate(token)
```

<table>
    <thead>
        <tr><th>Parameter</th><th>Type</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr>
            <td><code>token</code> _(required)_</td>
            <td><code>String</code></td>
            <td>A JWT previously issued by SurrealDB.</td>
        </tr>
    </tbody>
</table>

**Returns:** `JsonElement`

### `.auth()` {#auth}

Returns the record of the currently authenticated user.

```kotlin title="Method Syntax"
client.auth()
```

**Returns:** `JsonElement`

### `.invalidate()` {#invalidate}

Invalidates the current authentication for the session.

```kotlin title="Method Syntax"
client.invalidate()
```

**Returns:** `JsonElement`

### `.reset()` {#reset}

Resets the session to its initial, unauthenticated state.

```kotlin title="Method Syntax"
client.reset()
```

**Returns:** `JsonElement`

---

## Query methods

### `.query(sql, vars)` {#query}

Runs a raw [SurrealQL](/docs/reference/query-language.md) statement with optional bound parameters.

```kotlin title="Method Syntax"
client.query(sql, vars)
```

<table>
    <thead>
        <tr><th>Parameter</th><th>Type</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr>
            <td><code>sql</code> _(required)_</td>
            <td><code>String</code></td>
            <td>The SurrealQL to execute.</td>
        </tr>
        <tr>
            <td><code>vars</code></td>
            <td><code>JsonObject?</code></td>
            <td>Optional parameters bound as <code>$name</code> in the query.</td>
        </tr>
    </tbody>
</table>

**Returns:** `JsonElement`

```kotlin title="Example"
val result = client.query(
    "SELECT * FROM person WHERE age > \$min",
    buildJsonObject { put("min", 18) },
)
```

There is also an overload that accepts a `BoundQuery` built with the [`surql`](/docs/reference/kotlin/api/core/query-builder.md#surql) DSL.

### `.queryAs<T>(sql, vars)` {#query-as}

Runs SurrealQL and decodes the result into `T` using [`kotlinx.serialization`](/docs/reference/kotlin/concepts/serialization.md).

```kotlin title="Method Syntax"
client.queryAs<T>(sql, vars)
```

**Returns:** `T`

```kotlin title="Example"
val people: List<Person> = client.queryAs("SELECT * FROM person")
```

### `.decode<T>(element)` {#decode}

Decodes a [`JsonElement`](/docs/reference/kotlin/api/values/value.md) into `T` using the client's configured `Json` instance.

```kotlin title="Method Syntax"
client.decode<T>(element)
```

**Returns:** `T`

### `.let(key, value)` {#let}

Defines a session parameter referenced as `$key` in subsequent queries.

```kotlin title="Method Syntax"
client.let(key, value)
```

<table>
    <thead>
        <tr><th>Parameter</th><th>Type</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr>
            <td><code>key</code> _(required)_</td>
            <td><code>String</code></td>
            <td>The parameter name.</td>
        </tr>
        <tr>
            <td><code>value</code> _(required)_</td>
            <td><code>JsonElement</code></td>
            <td>The parameter value.</td>
        </tr>
    </tbody>
</table>

**Returns:** `JsonElement`

### `.unset(key)` {#unset}

Removes a previously defined session parameter.

```kotlin title="Method Syntax"
client.unset(key)
```

**Returns:** `JsonElement`

---

## CRUD methods

These methods return a [query builder](/docs/reference/kotlin/api/core/query-builder.md) that you refine and terminate with `await()` or [`awaitAs<T>()`](/docs/reference/kotlin/api/core/query-builder.md#await-as). The `what` argument accepts a [`Table`](/docs/reference/kotlin/api/values/table.md), [`RecordId`](/docs/reference/kotlin/api/values/record-id.md), or [`RecordIdRange`](/docs/reference/kotlin/api/values/record-id-range.md).

### `.select(what)` {#select}

Returns a [`SelectQuery`](/docs/reference/kotlin/api/core/query-builder.md#select-query) for reading records.

```kotlin title="Method Syntax"
client.select(what)
```

**Returns:** `SelectQuery`

```kotlin title="Example"
val all: List<Person> = client.select(Table("person")).awaitAs()
```

### `.create(what)` {#create}

Returns a [`CreateQuery`](/docs/reference/kotlin/api/core/query-builder.md#content-builders) for inserting a record.

```kotlin title="Method Syntax"
client.create(what)
```

**Returns:** `CreateQuery`

### `.update(what)` {#update}

Returns an `UpdateQuery` for replacing record content.

```kotlin title="Method Syntax"
client.update(what)
```

**Returns:** `UpdateQuery`

### `.upsert(what)` {#upsert}

Returns an `UpsertQuery` for creating or updating records.

```kotlin title="Method Syntax"
client.upsert(what)
```

**Returns:** `UpsertQuery`

### `.merge(what, data)` {#merge}

Returns a `MergeQuery` that merges `data` into the matched records.

```kotlin title="Method Syntax"
client.merge(what, data)
```

**Returns:** `MergeQuery`

### `.patch(what, patches, diff)` {#patch}

Returns a `PatchQuery` that applies [JSON Patch](https://jsonpatch.com/) operations.

```kotlin title="Method Syntax"
client.patch(what, patches, diff = false)
```

**Returns:** `PatchQuery`

### `.delete(what)` {#delete}

Returns a `DeleteQuery` for removing records.

```kotlin title="Method Syntax"
client.delete(what)
```

**Returns:** `DeleteQuery`

### `.relate(in, relation, out)` {#relate}

Returns a `RelateQuery` that creates a graph edge between two records.

```kotlin title="Method Syntax"
client.relate(`in`, relation, out)
```

**Returns:** `RelateQuery`

### `.insert(into, data)` {#insert}

Returns an `InsertQuery` that inserts one or more records into a [`Table`](/docs/reference/kotlin/api/values/table.md).

```kotlin title="Method Syntax"
client.insert(into, data)
```

**Returns:** `InsertQuery`

### `.insertRelation(into, data)` {#insert-relation}

Returns an `InsertRelationQuery` that inserts relation records into a [`Table`](/docs/reference/kotlin/api/values/table.md).

```kotlin title="Method Syntax"
client.insertRelation(into, data)
```

**Returns:** `InsertRelationQuery`

### `.run(function)` {#run}

Returns a `RunQuery` that invokes a built-in or custom [function](/docs/reference/query-language/functions/database-functions.md).

```kotlin title="Method Syntax"
client.run(function)
```

**Returns:** `RunQuery`

---

## Live query methods

### `.live(table, diff)` {#live}

Starts a [live query](/docs/reference/kotlin/concepts/live-queries.md) and returns a [`LiveQuerySubscription`](/docs/reference/kotlin/api/core/live-subscription.md). **WebSocket only.**

```kotlin title="Method Syntax"
client.live(table, diff = null)
```

<table>
    <thead>
        <tr><th>Parameter</th><th>Type</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr>
            <td><code>table</code> _(required)_</td>
            <td><code>String</code></td>
            <td>The table to watch.</td>
        </tr>
        <tr>
            <td><code>diff</code></td>
            <td><code>Boolean?</code></td>
            <td>When <code>true</code>, emit JSON Patch diffs instead of full records.</td>
        </tr>
    </tbody>
</table>

**Returns:** `LiveQuerySubscription`

### `.kill(liveQueryId)` {#kill}

Kills a live query by its ID. **WebSocket only.**

```kotlin title="Method Syntax"
client.kill(liveQueryId)
```

**Returns:** `JsonElement`

---

## Sessions

### `.newSession()` {#new-session}

Creates a new isolated [`SurrealSession`](/docs/reference/kotlin/api/core/session.md) over the same connection. **WebSocket only.**

```kotlin title="Method Syntax"
client.newSession()
```

**Returns:** `SurrealSession`

### `.closeSession(session)` {#close-session}

Closes a session previously created with [`.newSession()`](#new-session).

```kotlin title="Method Syntax"
client.closeSession(session)
```

**Returns:** `Unit`

---

## Properties

<table>
    <thead>
        <tr><th>Property</th><th>Type</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr>
            <td><code>config</code></td>
            <td><code>SurrealClientConfig</code></td>
            <td>The configuration the client was created with.</td>
        </tr>
        <tr>
            <td><code>features</code></td>
            <td><code>Set&lt;SurrealFeature&gt;</code></td>
            <td>The features supported by the active transport.</td>
        </tr>
        <tr>
            <td><code>connectionEvents</code></td>
            <td><code>SharedFlow&lt;SurrealConnectionEvent&gt;</code></td>
            <td>A flow of connection lifecycle events.</td>
        </tr>
        <tr>
            <td id="json"><code>json</code></td>
            <td><code>Json</code></td>
            <td>The <code>kotlinx.serialization</code> instance used for encoding and decoding.</td>
        </tr>
    </tbody>
</table>

## Learn more

- [Client configuration](/docs/reference/kotlin/api/core/client-config.md)
- [Session](/docs/reference/kotlin/api/core/session.md)
- [Query builder](/docs/reference/kotlin/api/core/query-builder.md)
- [Features and events](/docs/reference/kotlin/api/features.md)
- [Errors](/docs/reference/kotlin/api/errors.md)

---

Source: https://surrealdb.com/docs/reference/kotlin/api/core/transaction

# SurrealTransaction

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

`SurrealTransaction` represents an in-progress [transaction](/docs/reference/kotlin/concepts/transactions.md). It is itself a queryable, so the [CRUD builders](/docs/reference/kotlin/api/core/query-builder.md) are available scoped to the transaction. Transactions are started with the extension functions on a [session](/docs/reference/kotlin/api/core/session.md) and require the **WebSocket** transport.

**Source:** [surrealdb.kotlin](https://github.com/surrealdb/surrealdb.kotlin)

```kotlin title="Import"
import com.surrealdb.kotlin.beginTransaction
import com.surrealdb.kotlin.transaction
```

---

## `session.transaction { }` {#transaction-block}

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

```kotlin title="Method Syntax"
session.transaction { /* ... */ }
```

<table>
    <thead>
        <tr><th>Parameter</th><th>Type</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr>
            <td><code>block</code> _(required)_</td>
            <td><code>suspend SurrealTransaction.() -&gt; Unit</code></td>
            <td>The operations to run inside the transaction.</td>
        </tr>
    </tbody>
</table>

**Returns:** `Unit`

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

## `session.beginTransaction()` {#begin-transaction}

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

```kotlin title="Method Syntax"
session.beginTransaction()
```

**Returns:** `SurrealTransaction`

```kotlin title="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
}
```

---

## Methods

### `.commit()` {#commit}

Commits the transaction, persisting all its operations.

```kotlin title="Method Syntax"
tx.commit()
```

**Returns:** `Unit`

### `.cancel()` {#cancel}

Cancels the transaction, discarding all its operations.

```kotlin title="Method Syntax"
tx.cancel()
```

**Returns:** `Unit`

## Properties

<table>
    <thead>
        <tr><th>Property</th><th>Type</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr><td><code>txnId</code></td><td><code>String</code></td><td>The transaction's identifier.</td></tr>
    </tbody>
</table>

## Learn more

- [Transactions](/docs/reference/kotlin/concepts/transactions.md)
- [Session](/docs/reference/kotlin/api/core/session.md)
- [Query builders](/docs/reference/kotlin/api/core/query-builder.md)

---

Source: https://surrealdb.com/docs/reference/kotlin/api/errors

# Errors

The exception hierarchy raised by the SurrealDB Kotlin SDK.

The Kotlin SDK raises exceptions that all extend the sealed base class `SurrealException`. Because the hierarchy is sealed, you can branch over it exhaustively with `when`. See [Error handling](/docs/reference/kotlin/concepts/error-handling.md) for usage patterns and the [`Result` variants](/docs/reference/kotlin/concepts/executing-queries.md#result-variants) that avoid exceptions altogether.

**Source:** [surrealdb.kotlin](https://github.com/surrealdb/surrealdb.kotlin)

```kotlin title="Import"
import com.surrealdb.kotlin.error.SurrealException
```

---

## `SurrealException` {#surreal-exception}

The sealed base class of all SDK exceptions. Extends `RuntimeException`.

## `SurrealTransportException` {#transport}

Raised when the underlying connection fails, drops, or cannot be established.

## `SurrealProtocolException` {#protocol}

Raised when a malformed or unexpected message is received from the server.

## `SurrealRpcException` {#rpc}

Raised when the server returns an RPC error.

<table>
    <thead>
        <tr><th>Property</th><th>Type</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr><td><code>code</code></td><td><code>Int?</code></td><td>The RPC error code.</td></tr>
        <tr><td><code>data</code></td><td><code>JsonElement?</code></td><td>Additional error data from the server.</td></tr>
    </tbody>
</table>

## `SurrealAuthenticationException` {#authentication}

A subclass of [`SurrealRpcException`](#rpc) raised when authentication fails (for example, invalid credentials or an expired token).

## `SurrealFeatureNotSupportedException` {#feature-not-supported}

Raised when a feature is invoked that the current transport does not support - for example a [live query](/docs/reference/kotlin/concepts/live-queries.md) or [transaction](/docs/reference/kotlin/concepts/transactions.md) over HTTP. Extends the base [`SurrealException`](#surreal-exception). Guard against it with [`.supports()`](/docs/reference/kotlin/api/core/surreal-client.md#supports).

```kotlin title="Example"
import com.surrealdb.kotlin.error.SurrealAuthenticationException
import com.surrealdb.kotlin.error.SurrealException

try {
    client.signin(buildJsonObject {
        put("user", "root")
        put("pass", "wrong")
    })
} catch (e: SurrealAuthenticationException) {
    println("authentication failed: ${e.message}")
} catch (e: SurrealException) {
    println("error: ${e.message}")
}
```

## Learn more

- [Error handling](/docs/reference/kotlin/concepts/error-handling.md)
- [Features and events](/docs/reference/kotlin/api/features.md)

---

Source: https://surrealdb.com/docs/reference/kotlin/api/features

# Features & Events

Transport feature flags and connection lifecycle events in the SurrealDB Kotlin SDK.

The SDK exposes the capabilities of the active transport as a set of [`SurrealFeature`](#feature) values, and the lifecycle of the connection as a stream of [`SurrealConnectionEvent`](#connection-events).

**Source:** [surrealdb.kotlin](https://github.com/surrealdb/surrealdb.kotlin)

```kotlin title="Import"
import com.surrealdb.kotlin.SurrealFeature
import com.surrealdb.kotlin.engine.SurrealConnectionEvent
```

---

## `SurrealFeature` {#feature}

An enum of the features a transport may support. Inspect the active set via the [`features`](/docs/reference/kotlin/api/core/surreal-client.md#properties) property, or check a single feature with [`.supports()`](/docs/reference/kotlin/api/core/surreal-client.md#supports).

<table>
    <thead>
        <tr><th>Value</th><th>Available on</th></tr>
    </thead>
    <tbody>
        <tr><td><code>LiveQueries</code></td><td>WebSocket</td></tr>
        <tr><td><code>Transactions</code></td><td>WebSocket</td></tr>
        <tr><td><code>Sessions</code></td><td>WebSocket</td></tr>
        <tr><td><code>RefreshTokens</code></td><td>WebSocket</td></tr>
        <tr><td><code>ExportImport</code></td><td>WebSocket, HTTP</td></tr>
        <tr><td><code>SurrealML</code></td><td>WebSocket, HTTP, against SurrealDB 3.x or earlier. SurrealDB 4.0 removed SurrealML.</td></tr>
    </tbody>
</table>

```kotlin title="Example"
if (client.supports(SurrealFeature.LiveQueries)) {
    val subscription = client.live("person")
}
```

---

## `SurrealConnectionEvent` {#connection-events}

A sealed class emitted on the client's [`connectionEvents`](/docs/reference/kotlin/api/core/surreal-client.md#properties) [`SharedFlow`](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-shared-flow/).

<table>
    <thead>
        <tr><th>Variant</th><th>Payload</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr><td><code>Connecting</code></td><td>-</td><td>A connection attempt has started.</td></tr>
        <tr><td><code>Connected</code></td><td>-</td><td>The connection is established.</td></tr>
        <tr><td><code>Disconnected</code></td><td>-</td><td>The connection has dropped.</td></tr>
        <tr><td><code>Reconnecting</code></td><td><code>attempt: Int</code>, <code>delayMillis: Long</code></td><td>A reconnect is scheduled.</td></tr>
        <tr><td><code>Error</code></td><td><code>cause: Throwable</code></td><td>A connection error occurred.</td></tr>
    </tbody>
</table>

```kotlin title="Example"
client.connectionEvents.collect { event ->
    when (event) {
        is SurrealConnectionEvent.Connected -> println("connected")
        is SurrealConnectionEvent.Reconnecting ->
            println("attempt ${event.attempt}")
        is SurrealConnectionEvent.Error ->
            println("error: ${event.cause.message}")
        else -> {}
    }
}
```

## Learn more

- [Connecting to SurrealDB](/docs/reference/kotlin/concepts/connecting-to-surrealdb.md)
- [SurrealClient API reference](/docs/reference/kotlin/api/core/surreal-client.md)

---

Source: https://surrealdb.com/docs/reference/kotlin/api/values/record-id

# RecordId

The RecordId type identifies a single record in the SurrealDB Kotlin SDK.

`RecordId` identifies a single record by its table and ID, rendered as `table:id`. Pass it to the [CRUD builders](/docs/reference/kotlin/concepts/data-manipulation.md) to target one record.

**Source:** [surrealdb.kotlin](https://github.com/surrealdb/surrealdb.kotlin)

```kotlin title="Import"
import com.surrealdb.kotlin.query.RecordId
```

---

## Constructor

```kotlin title="Method Syntax"
RecordId(table, id)
```

<table>
    <thead>
        <tr><th>Parameter</th><th>Type</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr><td><code>table</code> _(required)_</td><td><code>String</code></td><td>The table name.</td></tr>
        <tr><td><code>id</code> _(required)_</td><td><code>String</code></td><td>The record identifier within the table.</td></tr>
    </tbody>
</table>

```kotlin title="Example"
val ada = RecordId("person", "ada")

client.select(ada).awaitAs<Person>()
```

When bound into a query, a `RecordId` is rendered with `type::record(table, id)` so the value is always passed safely.

## Learn more

- [Value types](/docs/reference/kotlin/concepts/value-types.md)
- [`Table`](/docs/reference/kotlin/api/values/table.md) and [`RecordIdRange`](/docs/reference/kotlin/api/values/record-id-range.md)

---

Source: https://surrealdb.com/docs/reference/kotlin/api/values/record-id-range

# RecordIdRange

The RecordIdRange type targets a range of records within a table in the SurrealDB Kotlin SDK.

`RecordIdRange` targets a contiguous range of records within a table by their IDs. Pass it to the [CRUD builders](/docs/reference/kotlin/concepts/data-manipulation.md) to operate on a [range of records](/docs/reference/query-language/language-primitives/data-types/record-ids.md#record-ranges).

**Source:** [surrealdb.kotlin](https://github.com/surrealdb/surrealdb.kotlin)

```kotlin title="Import"
import com.surrealdb.kotlin.query.RecordIdRange
```

---

## Constructor

```kotlin title="Method Syntax"
RecordIdRange(table, start, end, includeEnd)
```

<table>
    <thead>
        <tr><th>Parameter</th><th>Type</th><th>Default</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr><td><code>table</code> _(required)_</td><td><code>String</code></td><td>-</td><td>The table name.</td></tr>
        <tr><td><code>start</code></td><td><code>String?</code></td><td><code>null</code></td><td>The inclusive start ID, or <code>null</code> for unbounded.</td></tr>
        <tr><td><code>end</code></td><td><code>String?</code></td><td><code>null</code></td><td>The end ID, or <code>null</code> for unbounded.</td></tr>
        <tr><td><code>includeEnd</code></td><td><code>Boolean</code></td><td><code>false</code></td><td>Whether the <code>end</code> ID is inclusive.</td></tr>
    </tbody>
</table>

```kotlin title="Example"
val range = RecordIdRange(
    "person",
    start = "a",
    end = "m",
    includeEnd = true,
)

client.select(range).awaitAs<List<Person>>()
```

## Learn more

- [Value types](/docs/reference/kotlin/concepts/value-types.md)
- [`RecordId`](/docs/reference/kotlin/api/values/record-id.md) and [`Table`](/docs/reference/kotlin/api/values/table.md)
- [Record ranges](/docs/reference/query-language/language-primitives/data-types/record-ids.md#record-ranges) in SurrealQL

---

Source: https://surrealdb.com/docs/reference/kotlin/api/values/table

# Table

The Table type refers to a table by name in the SurrealDB Kotlin SDK.

`Table` refers to a table by name. Pass it to the [CRUD builders](/docs/reference/kotlin/concepts/data-manipulation.md) to target every record in the table.

**Source:** [surrealdb.kotlin](https://github.com/surrealdb/surrealdb.kotlin)

```kotlin title="Import"
import com.surrealdb.kotlin.query.Table
```

---

## Constructor

```kotlin title="Method Syntax"
Table(name)
```

<table>
    <thead>
        <tr><th>Parameter</th><th>Type</th><th>Description</th></tr>
    </thead>
    <tbody>
        <tr><td><code>name</code> _(required)_</td><td><code>String</code></td><td>The table name.</td></tr>
    </tbody>
</table>

```kotlin title="Example"
val person = Table("person")

client.select(person).awaitAs<List<Person>>()
```

When bound into a query, a `Table` is rendered with `type::table(name)` so the value is always passed safely.

## Learn more

- [Value types](/docs/reference/kotlin/concepts/value-types.md)
- [`RecordId`](/docs/reference/kotlin/api/values/record-id.md) and [`RecordIdRange`](/docs/reference/kotlin/api/values/record-id-range.md)

---

Source: https://surrealdb.com/docs/reference/kotlin/api/values/value

# Value (JSON model)

How the SurrealDB Kotlin SDK models values using kotlinx.serialisation JSON types.

The Kotlin SDK models all data - beyond the dedicated [record types](/docs/reference/kotlin/api/values/record-id.md) - using [`kotlinx.serialization`](/docs/reference/kotlin/concepts/serialization.md) JSON types. Read methods return a [`JsonElement`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-element/); write methods accept a [`JsonObject`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-object/).

**Source:** [surrealdb.kotlin](https://github.com/surrealdb/surrealdb.kotlin)

```kotlin title="Import"
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
```

---

## Building values

Construct objects with [`buildJsonObject`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/build-json-object.html).

```kotlin title="Example"
val data = buildJsonObject {
    put("name", "Ada")
    put("age", 36)
}
```

## Decoding values

Rather than navigating raw `JsonElement` trees, decode results into your own [`@Serializable`](/docs/reference/kotlin/concepts/serialization.md) types with [`.queryAs<T>()`](/docs/reference/kotlin/api/core/surreal-client.md#query-as), [`.awaitAs<T>()`](/docs/reference/kotlin/api/core/query-builder.md#await-as), or [`.decode<T>()`](/docs/reference/kotlin/api/core/surreal-client.md#decode).

```kotlin title="Example"
val people: List<Person> = client.queryAs("SELECT * FROM person")
```

> [!NOTE]
> The SDK does not provide dedicated wrapper classes for datetimes, durations, or geometries. Express these as SurrealQL literals or the JSON values SurrealDB expects, and decode results into your own types.

## Learn more

- [Value types](/docs/reference/kotlin/concepts/value-types.md)
- [Serialisation](/docs/reference/kotlin/concepts/serialization.md)

---

Source: https://surrealdb.com/docs/reference/kotlin/concepts/authentication

# Authentication

Sign up, sign in, and manage authentication tokens with the SurrealDB Kotlin SDK.

The Kotlin SDK supports the full range of SurrealDB [authentication](/docs/learn/security/authentication/users.md) methods: root, namespace, and database users, as well as record (scoped) access. Credentials are supplied as a [`JsonObject`](/docs/reference/kotlin/concepts/value-types.md), built with [`buildJsonObject`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/build-json-object.html).

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Method</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#signup"><code>client.signup(params)</code></a></td>
			<td scope="row" data-label="Description">Signs up against a record access method</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#signin"><code>client.signin(params)</code></a></td>
			<td scope="row" data-label="Description">Signs in with credentials</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#authenticate"><code>client.authenticate(token)</code></a></td>
			<td scope="row" data-label="Description">Authenticates with an existing token</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#auth"><code>client.auth()</code></a></td>
			<td scope="row" data-label="Description">Returns the current authentication record</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#invalidate"><code>client.invalidate()</code></a></td>
			<td scope="row" data-label="Description">Invalidates the current session authentication</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#reset"><code>client.reset()</code></a></td>
			<td scope="row" data-label="Description">Resets the session to an unauthenticated state</td>
		</tr>
	</tbody>
</table>

## Signing in

Use [`.signin()`](/docs/reference/kotlin/api/core/surreal-client.md#signin) with the credentials appropriate to the [level of access](/docs/learn/security/authentication/users.md) you need. It returns the authentication token as a [`JsonElement`](/docs/reference/kotlin/concepts/value-types.md).

```kotlin
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

// Root user
client.signin(buildJsonObject {
    put("user", "root")
    put("pass", "root")
})

// Database user
client.signin(buildJsonObject {
    put("namespace", "surrealdb")
    put("database", "docs")
    put("user", "admin")
    put("pass", "secret")
})
```

## Signing up

Use [`.signup()`](/docs/reference/kotlin/api/core/surreal-client.md#signup) to register against a [record access](/docs/reference/query-language/statements/define/access/record.md) method.

```kotlin
val token = client.signup(buildJsonObject {
    put("namespace", "surrealdb")
    put("database", "docs")
    put("access", "user")
    put("email", "ada@example.com")
    put("password", "hunter2")
})
```

## Authenticating with a token

If you already hold a token (for example from a previous session), authenticate the connection with [`.authenticate()`](/docs/reference/kotlin/api/core/surreal-client.md#authenticate).

```kotlin
client.authenticate("eyJ0eXAiOiJKV1Qi...")
```

## Inspecting and clearing authentication

Retrieve the currently authenticated record with [`.auth()`](/docs/reference/kotlin/api/core/surreal-client.md#auth), drop the authentication while keeping the connection open with [`.invalidate()`](/docs/reference/kotlin/api/core/surreal-client.md#invalidate), or fully reset the session state with [`.reset()`](/docs/reference/kotlin/api/core/surreal-client.md#reset).

```kotlin
val me = client.auth()
client.invalidate()
client.reset()
```

## Automatic authentication and token renewal

The client can authenticate automatically on connect and after reconnects, and renew tokens shortly before they expire. Provide a `credentialProvider` and enable `autoAuthenticate` on your [`SurrealClientConfig`](/docs/reference/kotlin/api/core/client-config.md). The provider returns a [`SurrealAuthInput`](/docs/reference/kotlin/api/core/client-config.md#surreal-auth-input) - either a `SignIn` with credentials or an existing `Token`.

```kotlin
import com.surrealdb.kotlin.SurrealAuthInput
import com.surrealdb.kotlin.SurrealClientConfig
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

val client = SurrealClient(
    SurrealClientConfig(
        url = "wss://example.com",
        autoAuthenticate = true,
        tokenRenewalLeadMillis = 60_000, // renew 60s before expiry
        credentialProvider = {
            SurrealAuthInput.SignIn(buildJsonObject {
                put("user", "root")
                put("pass", "root")
            })
        },
    ),
)
```

## Learn more

- [SurrealClient API reference](/docs/reference/kotlin/api/core/surreal-client.md) for complete method signatures
- [Client configuration](/docs/reference/kotlin/api/core/client-config.md) for `credentialProvider` and renewal options
- [Multiple sessions](/docs/reference/kotlin/concepts/multiple-sessions.md) for per-session authentication
- [SurrealDB authentication](/docs/learn/security/authentication/users.md) for an overview of authentication concepts

---

Source: https://surrealdb.com/docs/reference/kotlin/concepts/connecting-to-surrealdb

# Connecting to SurrealDB

The Kotlin SDK connects to SurrealDB over WebSocket or HTTP, with automatic transport selection and reconnection.

The first step towards interacting with [SurrealDB](/docs) is to create a connection to a database instance. This involves constructing a [`SurrealClient`](/docs/reference/kotlin/api/core/surreal-client.md) with a [`SurrealClientConfig`](/docs/reference/kotlin/api/core/client-config.md), then selecting a namespace and database. The SDK supports remote connections over WebSocket and HTTP.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Method</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#constructor"><code>SurrealClient(config)</code></a></td>
			<td scope="row" data-label="Description">Creates a new client from a configuration</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#connect"><code>client.connect()</code></a></td>
			<td scope="row" data-label="Description">Establishes the connection explicitly</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#close"><code>client.close()</code></a></td>
			<td scope="row" data-label="Description">Closes the connection and releases resources</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#use"><code>client.use(ns, db)</code></a></td>
			<td scope="row" data-label="Description">Selects a namespace and database</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#version"><code>client.version()</code></a></td>
			<td scope="row" data-label="Description">Returns the server version</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#ping"><code>client.ping()</code></a></td>
			<td scope="row" data-label="Description">Pings the server</td>
		</tr>
	</tbody>
</table>

## Opening a connection

Construct a [`SurrealClient`](/docs/reference/kotlin/api/core/surreal-client.md) with a [`SurrealClientConfig`](/docs/reference/kotlin/api/core/client-config.md) whose `url` points at your SurrealDB instance. By default (`autoConnect = true`) the client connects lazily on the first request, so you rarely need to call [`.connect()`](/docs/reference/kotlin/api/core/surreal-client.md#connect) yourself.

```kotlin
import com.surrealdb.kotlin.SurrealClient
import com.surrealdb.kotlin.SurrealClientConfig

val client = SurrealClient(SurrealClientConfig(url = "ws://localhost:8000"))
```

## Connection string protocols

The URL scheme determines the transport. For more on server configuration, see the [start command](/docs/reference/cli/db/commands/start.md) documentation.

| Protocol | Description |
|---|---|
| `ws://` | Plain WebSocket connection |
| `wss://` | Secure WebSocket connection (TLS) |
| `http://` | Plain HTTP connection |
| `https://` | Secure HTTP connection (TLS) |

The WebSocket engine maintains a single long-lived connection, while the HTTP engine issues a request per call.

## Feature support by protocol

Not all features are available on every transport. You can check support at runtime with [`.supports()`](/docs/reference/kotlin/api/core/surreal-client.md#supports); unsupported calls throw [`SurrealFeatureNotSupportedException`](/docs/reference/kotlin/api/errors.md).

| Feature | WebSocket | HTTP |
|---|---|---|
| Authentication | Yes | Yes |
| Queries | Yes | Yes |
| CRUD operations | Yes | Yes |
| Live queries | Yes | No |
| Transactions | Yes | No |
| Multiple sessions | Yes | No |
| Refresh tokens | Yes | No |
| Export / Import | Yes | Yes |
| SurrealML (SurrealDB 3.x or earlier) | Yes | Yes |

See [Features and events](/docs/reference/kotlin/api/features.md) for the full [`SurrealFeature`](/docs/reference/kotlin/api/features.md#feature) enum.

## Selecting a namespace and database

After connecting, select a [namespace](/docs/reference/query-language/statements/define/namespace.md) and [database](/docs/reference/query-language/statements/define/database.md) with [`.use()`](/docs/reference/kotlin/api/core/surreal-client.md#use).

```kotlin
client.use("surrealdb", "docs")
```

## Reconnection

The WebSocket engine automatically reconnects with exponential backoff. Tune this through the [`ReconnectConfig`](/docs/reference/kotlin/api/core/client-config.md#reconnect-config) on your [`SurrealClientConfig`](/docs/reference/kotlin/api/core/client-config.md).

```kotlin
import com.surrealdb.kotlin.SurrealClientConfig
import com.surrealdb.kotlin.engine.ReconnectConfig

val client = SurrealClient(
    SurrealClientConfig(
        url = "wss://example.com",
        reconnect = ReconnectConfig(
            enabled = true,
            initialDelayMillis = 250,
            maxDelayMillis = 30_000,
            multiplier = 1.5,
            maxAttempts = null, // null means retry indefinitely
        ),
    ),
)
```

## Observing connection events

The client exposes a [`connectionEvents`](/docs/reference/kotlin/api/features.md#connection-events) [`SharedFlow`](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-shared-flow/) you can collect to react to lifecycle changes.

```kotlin
import com.surrealdb.kotlin.engine.SurrealConnectionEvent
import kotlinx.coroutines.launch

scope.launch {
    client.connectionEvents.collect { event ->
        when (event) {
            is SurrealConnectionEvent.Connected -> println("connected")
            is SurrealConnectionEvent.Reconnecting ->
                println("reconnecting, attempt ${event.attempt}")
            is SurrealConnectionEvent.Disconnected -> println("disconnected")
            is SurrealConnectionEvent.Error ->
                println("error: ${event.cause.message}")
            else -> {}
        }
    }
}
```

## Closing a connection

Call [`.close()`](/docs/reference/kotlin/api/core/surreal-client.md#close) to release all resources associated with the connection.

```kotlin
client.close()
```

## Learn more

- [SurrealClient API reference](/docs/reference/kotlin/api/core/surreal-client.md) for complete method signatures
- [Client configuration](/docs/reference/kotlin/api/core/client-config.md) for all configuration options
- [Authentication](/docs/reference/kotlin/concepts/authentication.md) for signing in and managing sessions
- [Error handling](/docs/reference/kotlin/concepts/error-handling.md) for handling connection errors

---

Source: https://surrealdb.com/docs/reference/kotlin/concepts/data-manipulation

# Data manipulation

Create, read, update, and delete records with the fluent builders in the SurrealDB Kotlin SDK.

The Kotlin SDK provides fluent builders for the common CRUD operations. Each builder method (such as [`.select()`](/docs/reference/kotlin/api/core/surreal-client.md#select) or [`.create()`](/docs/reference/kotlin/api/core/surreal-client.md#create)) returns a [query builder](/docs/reference/kotlin/api/core/query-builder.md) that you refine and then terminate with `await()` (raw [`JsonElement`](/docs/reference/kotlin/concepts/value-types.md)) or the typed [`awaitAs<T>()`](/docs/reference/kotlin/api/core/query-builder.md#await-as) extension. Internally these compile to [SurrealQL](/docs/reference/query-language.md) and dispatch through [`.query()`](/docs/reference/kotlin/concepts/executing-queries.md), mirroring the [JavaScript SDK](/docs/languages/javascript.md).

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Method</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#select"><code>client.select(what)</code></a></td>
			<td scope="row" data-label="Description">Selects records from a table or record</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#create"><code>client.create(what)</code></a></td>
			<td scope="row" data-label="Description">Creates a record</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#update"><code>client.update(what)</code></a></td>
			<td scope="row" data-label="Description">Replaces the content of records</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#upsert"><code>client.upsert(what)</code></a></td>
			<td scope="row" data-label="Description">Creates or updates records</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#merge"><code>client.merge(what, data)</code></a></td>
			<td scope="row" data-label="Description">Merges data into records</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#patch"><code>client.patch(what, patches)</code></a></td>
			<td scope="row" data-label="Description">Applies JSON patches to records</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#delete"><code>client.delete(what)</code></a></td>
			<td scope="row" data-label="Description">Deletes records</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#relate"><code>client.relate(in, relation, out)</code></a></td>
			<td scope="row" data-label="Description">Creates a graph edge between records</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#insert"><code>client.insert(into, data)</code></a></td>
			<td scope="row" data-label="Description">Inserts one or more records</td>
		</tr>
	</tbody>
</table>

The `what` argument accepts a [`Table`](/docs/reference/kotlin/api/values/table.md) to target every record in a table, a [`RecordId`](/docs/reference/kotlin/api/values/record-id.md) to target a single record, or a [`RecordIdRange`](/docs/reference/kotlin/api/values/record-id-range.md) to target a range.

## Creating records

Build content with [`buildJsonObject`](/docs/reference/kotlin/concepts/value-types.md) and finish with the typed [`awaitAs<T>()`](/docs/reference/kotlin/api/core/query-builder.md#await-as).

```kotlin
import com.surrealdb.kotlin.query.RecordId
import com.surrealdb.kotlin.query.awaitAs
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

@Serializable
data class Person(val name: String, val age: Int)

val ada: Person = client
    .create(RecordId("person", "ada"))
    .content(buildJsonObject {
        put("name", "Ada")
        put("age", 36)
    })
    .awaitAs()
```

## Selecting records

Refine a [`select`](/docs/reference/kotlin/api/core/query-builder.md#select-query) with [`.where()`](/docs/reference/kotlin/api/core/query-builder.md), [`.limit()`](/docs/reference/kotlin/api/core/query-builder.md), [`.start()`](/docs/reference/kotlin/api/core/query-builder.md), [`.fetch()`](/docs/reference/kotlin/api/core/query-builder.md), and others, using the [expression helpers](/docs/reference/kotlin/api/core/query-builder.md#expressions).

```kotlin
import com.surrealdb.kotlin.query.Table
import com.surrealdb.kotlin.query.field
import com.surrealdb.kotlin.query.gte
import com.surrealdb.kotlin.query.awaitAs

val adults: List<Person> = client
    .select(Table("person"))
    .where(field("age") gte 18)
    .limit(50)
    .awaitAs()
```

## Updating and merging

Use [`.update()`](/docs/reference/kotlin/api/core/surreal-client.md#update) to replace record content, [`.merge()`](/docs/reference/kotlin/api/core/surreal-client.md#merge) to merge data, or [`.upsert()`](/docs/reference/kotlin/api/core/surreal-client.md#upsert) to create or update. Control the returned payload with [`.returnMode()`](/docs/reference/kotlin/api/core/query-builder.md#return-mode-type).

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

client
    .merge(RecordId("person", "ada"), buildJsonObject { put("age", 37) })
    .returnMode(ReturnMode.After)
    .await()
```

## Deleting records

```kotlin
import com.surrealdb.kotlin.query.RecordId

client.delete(RecordId("person", "ada")).await()
```

## Relating records

Create a graph edge between two records with [`.relate()`](/docs/reference/kotlin/api/core/surreal-client.md#relate).

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

client
    .relate(
        RecordId("person", "ada"),
        RecordId("wrote", "w1"),
        RecordId("article", "a1"),
    )
    .content(buildJsonObject { put("year", 1843) })
    .await()
```

## Learn more

- [Query builder reference](/docs/reference/kotlin/api/core/query-builder.md) for every builder method and expression helper
- [Executing queries](/docs/reference/kotlin/concepts/executing-queries.md) for raw SurrealQL
- [Value types](/docs/reference/kotlin/concepts/value-types.md) for `Table`, `RecordId`, and the JSON model
- [Serialisation](/docs/reference/kotlin/concepts/serialization.md) for decoding into your own types

---

Source: https://surrealdb.com/docs/reference/kotlin/concepts/error-handling

# Error handling

Handle exceptions and feature-support errors raised by the SurrealDB Kotlin SDK.

Networked operations on the SDK throw a [`SurrealException`](/docs/reference/kotlin/api/errors.md) on failure, or you can use the [`Result` variants](/docs/reference/kotlin/concepts/executing-queries.md#result-variants) to handle failures functionally without exceptions.

The error kinds, wire codes and structured shape behind these are documented once in [Errors](/docs/reference/protocols/errors.md), which applies to every SDK and protocol.

## Exception hierarchy

All SDK exceptions extend the sealed base [`SurrealException`](/docs/reference/kotlin/api/errors.md).

| Exception | Raised when |
|---|---|
| [`SurrealTransportException`](/docs/reference/kotlin/api/errors.md#transport) | The connection fails or drops |
| [`SurrealProtocolException`](/docs/reference/kotlin/api/errors.md#protocol) | A malformed or unexpected protocol message is received |
| [`SurrealRpcException`](/docs/reference/kotlin/api/errors.md#rpc) | The server returns an RPC error (carries `code` and `data`) |
| [`SurrealAuthenticationException`](/docs/reference/kotlin/api/errors.md#authentication) | Authentication fails (a subclass of `SurrealRpcException`) |
| [`SurrealFeatureNotSupportedException`](/docs/reference/kotlin/api/errors.md#feature-not-supported) | A feature is unavailable on the current transport |

## Catching exceptions

Because [`SurrealException`](/docs/reference/kotlin/api/errors.md) is a sealed class, you can exhaustively branch on it with `when`.

```kotlin
import com.surrealdb.kotlin.error.SurrealAuthenticationException
import com.surrealdb.kotlin.error.SurrealException
import com.surrealdb.kotlin.error.SurrealRpcException
import com.surrealdb.kotlin.error.SurrealTransportException

try {
    client.signin(buildJsonObject {
        put("user", "root")
        put("pass", "wrong")
    })
} catch (e: SurrealAuthenticationException) {
    println("bad credentials: ${e.message}")
} catch (e: SurrealRpcException) {
    println("server error ${e.code}: ${e.message}")
} catch (e: SurrealTransportException) {
    println("connection problem: ${e.message}")
} catch (e: SurrealException) {
    println("unexpected: ${e.message}")
}
```

## Feature support errors

Calling a feature that the current transport does not support - for example a [live query](/docs/reference/kotlin/concepts/live-queries.md) over HTTP - throws [`SurrealFeatureNotSupportedException`](/docs/reference/kotlin/api/errors.md#feature-not-supported). Guard against this with [`.supports()`](/docs/reference/kotlin/api/core/surreal-client.md#supports).

```kotlin
import com.surrealdb.kotlin.SurrealFeature

if (client.supports(SurrealFeature.LiveQueries)) {
    val subscription = client.live("person")
}
```

## Using Result variants

Each networked method has a `...Result` companion that wraps the outcome in a [`Result`](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-result/) instead of throwing.

```kotlin
client.queryResult("SELECT * FROM person")
    .onSuccess { println("got $it") }
    .onFailure { println("failed: ${it.message}") }
```

## Learn more

- [Errors reference](/docs/reference/kotlin/api/errors.md) for every exception type
- [Features and events](/docs/reference/kotlin/api/features.md) for checking transport support
- [Executing queries](/docs/reference/kotlin/concepts/executing-queries.md) for the `Result` variants

---

Source: https://surrealdb.com/docs/reference/kotlin/concepts/executing-queries

# Executing queries

Run raw SurrealQL with bound parameters and decode results with the Kotlin SDK.

The [`.query()`](/docs/reference/kotlin/api/core/surreal-client.md#query) family runs raw [SurrealQL](/docs/reference/query-language.md) and is the foundation of the SDK - the [CRUD builders](/docs/reference/kotlin/concepts/data-manipulation.md) compile to SurrealQL and dispatch through it. Queries can be supplied as a string with a [`JsonObject`](/docs/reference/kotlin/concepts/value-types.md) of bound parameters, or built with the [`surql`](#building-queries) DSL.

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Method</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#query"><code>client.query(sql, vars)</code></a></td>
			<td scope="row" data-label="Description">Runs SurrealQL and returns the raw result</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#query-as"><code>client.queryAs&lt;T&gt;(sql, vars)</code></a></td>
			<td scope="row" data-label="Description">Runs SurrealQL and decodes the result to <code>T</code></td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#query"><code>client.queryResult(sql, vars)</code></a></td>
			<td scope="row" data-label="Description">Runs SurrealQL and returns a <code>Result</code></td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#let"><code>client.let(key, value)</code></a></td>
			<td scope="row" data-label="Description">Defines a session parameter</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#unset"><code>client.unset(key)</code></a></td>
			<td scope="row" data-label="Description">Removes a session parameter</td>
		</tr>
	</tbody>
</table>

## Running a query

Pass SurrealQL and, optionally, a [`JsonObject`](/docs/reference/kotlin/concepts/value-types.md) of bound parameters. The result is returned as a [`JsonElement`](/docs/reference/kotlin/concepts/value-types.md).

```kotlin
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

val result = client.query(
    "SELECT * FROM person WHERE age > \$min_age",
    buildJsonObject { put("min_age", 25) },
)
```

> [!NOTE]
> Always bind variables with the `vars` argument rather than interpolating values into the query string. This avoids SurrealQL injection and lets the server cache query plans.

## Decoding results

To decode a query result straight into your own types, use the inline [`.queryAs<T>()`](/docs/reference/kotlin/api/core/surreal-client.md#query-as) helper with a [`@Serializable`](/docs/reference/kotlin/concepts/serialization.md) type.

```kotlin
import kotlinx.serialization.Serializable

@Serializable
data class Person(val name: String, val age: Int)

val people: List<Person> = client.queryAs(
    "SELECT * FROM person WHERE age > \$min_age",
    buildJsonObject { put("min_age", 25) },
)
```

You can also decode an arbitrary [`JsonElement`](/docs/reference/kotlin/concepts/value-types.md) yourself with [`.decode<T>()`](/docs/reference/kotlin/api/core/surreal-client.md#decode).

## Result variants

Every networked call has a `...Result` companion that returns a [`Result`](https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-result/) instead of throwing, which is useful when you prefer to handle failures functionally.

```kotlin
val outcome = client.queryResult("SELECT * FROM person")
outcome
    .onSuccess { println("got $it") }
    .onFailure { println("query failed: ${it.message}") }
```

See [Error handling](/docs/reference/kotlin/concepts/error-handling.md) for the exception hierarchy thrown by the non-`Result` variants.

## Session parameters

Define parameters that persist for the session with [`.let()`](/docs/reference/kotlin/api/core/surreal-client.md#let), and remove them with [`.unset()`](/docs/reference/kotlin/api/core/surreal-client.md#unset). These are referenced as `$name` in subsequent queries.

```kotlin
import kotlinx.serialization.json.JsonPrimitive

client.let("min_age", JsonPrimitive(18))
client.query("SELECT * FROM person WHERE age > \$min_age")
client.unset("min_age")
```

## Building queries

The [`surql`](/docs/reference/kotlin/api/core/query-builder.md#surql) DSL builds a parameterised `BoundQuery` with automatic binding of values and record identifiers.

```kotlin
import com.surrealdb.kotlin.query.surql

val bound = surql("SELECT * FROM person WHERE age > \$min", "min" to 25)
val result = client.query(bound)
```

## Learn more

- [SurrealClient API reference](/docs/reference/kotlin/api/core/surreal-client.md) for complete method signatures
- [Query builder reference](/docs/reference/kotlin/api/core/query-builder.md) for the fluent builders and `surql` DSL
- [Data manipulation](/docs/reference/kotlin/concepts/data-manipulation.md) for CRUD with the builders
- [Serialisation](/docs/reference/kotlin/concepts/serialization.md) for working with `@Serializable` types

---

Source: https://surrealdb.com/docs/reference/kotlin/concepts/live-queries

# Live queries

Subscribe to real-time changes with live queries in the SurrealDB Kotlin SDK.

[Live queries](/docs/reference/query-language/statements/live-select.md) push changes to your application as records are created, updated, or deleted. In the Kotlin SDK, a live subscription exposes a coroutine [`Flow`](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.flow/-flow/) of notifications that you collect.

> [!NOTE]
> Live queries require a stateful connection and are only available over the **WebSocket** transport. Calling [`.live()`](/docs/reference/kotlin/api/core/surreal-client.md#live) over HTTP throws [`SurrealFeatureNotSupportedException`](/docs/reference/kotlin/api/errors.md). Check support with [`client.supports(SurrealFeature.LiveQueries)`](/docs/reference/kotlin/api/core/surreal-client.md#supports).

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Method</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#live"><code>client.live(table)</code></a></td>
			<td scope="row" data-label="Description">Starts a live query and returns a subscription</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/live-subscription.md#events"><code>subscription.events</code></a></td>
			<td scope="row" data-label="Description">A <code>Flow</code> of live notifications</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/live-subscription.md#cancel"><code>subscription.cancel()</code></a></td>
			<td scope="row" data-label="Description">Stops the subscription</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#kill"><code>client.kill(id)</code></a></td>
			<td scope="row" data-label="Description">Kills a live query by ID</td>
		</tr>
	</tbody>
</table>

## Starting a live query

Call [`.live()`](/docs/reference/kotlin/api/core/surreal-client.md#live) with a table name to receive a [`LiveQuerySubscription`](/docs/reference/kotlin/api/core/live-subscription.md), then collect its [`events`](/docs/reference/kotlin/api/core/live-subscription.md#events) flow. Each [`SurrealLiveNotification`](/docs/reference/kotlin/api/core/live-subscription.md#notification) carries an `action` (`"CREATE"`, `"UPDATE"`, or `"DELETE"`) and a `result` payload.

```kotlin
import com.surrealdb.kotlin.SurrealFeature
import kotlinx.coroutines.launch

if (client.supports(SurrealFeature.LiveQueries)) {
    val subscription = client.live("person")

    val job = scope.launch {
        subscription.events.collect { event ->
            println("${event.action}: ${event.result}")
        }
    }
}
```

Pass `diff = true` to receive [JSON Patch](https://jsonpatch.com/) diffs instead of the full record.

```kotlin
val subscription = client.live("person", diff = true)
```

## Filtered live queries

To watch a subset of records with a `WHERE` clause, run a `LIVE SELECT` statement through [`.query()`](/docs/reference/kotlin/concepts/executing-queries.md); the result is the live query UUID, which you can later pass to [`.kill()`](/docs/reference/kotlin/api/core/surreal-client.md#kill).

```kotlin
val liveId = client.query("LIVE SELECT * FROM person WHERE age >= 18")
```

## Stopping a subscription

Cancel a subscription started with [`.live()`](/docs/reference/kotlin/api/core/surreal-client.md#live) by calling [`.cancel()`](/docs/reference/kotlin/api/core/live-subscription.md#cancel), which also kills the underlying live query on the server. Cancel the collecting coroutine separately.

```kotlin
subscription.cancel()
job.cancel()
```

For live queries started via raw SurrealQL, kill them with their UUID.

```kotlin
client.kill(liveId.toString())
```

## Learn more

- [Live subscription reference](/docs/reference/kotlin/api/core/live-subscription.md) for the subscription and notification types
- [SurrealClient API reference](/docs/reference/kotlin/api/core/surreal-client.md) for `.live()` and `.kill()`
- [Features and events](/docs/reference/kotlin/api/features.md) for checking transport support
- [LIVE SELECT](/docs/reference/query-language/statements/live-select.md) for the SurrealQL statement

---

Source: https://surrealdb.com/docs/reference/kotlin/concepts/multiple-sessions

# Multiple sessions

Isolate authentication and state across concurrent sessions with the SurrealDB Kotlin SDK.

A single WebSocket connection can host multiple independent **sessions**, each with its own authentication, namespace, database, and parameters. This is useful for multi-tenant applications where requests act on behalf of different users over one shared connection. The [`SurrealClient`](/docs/reference/kotlin/api/core/surreal-client.md) is itself the root session.

> [!NOTE]
> Multiple sessions require a stateful connection and are only available over the **WebSocket** transport. Check support with [`client.supports(SurrealFeature.Sessions)`](/docs/reference/kotlin/api/core/surreal-client.md#supports).

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Method</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#new-session"><code>client.newSession()</code></a></td>
			<td scope="row" data-label="Description">Creates a new isolated session</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/surreal-client.md#close-session"><code>client.closeSession(session)</code></a></td>
			<td scope="row" data-label="Description">Closes a session</td>
		</tr>
	</tbody>
</table>

## Creating sessions

Each session created with [`.newSession()`](/docs/reference/kotlin/api/core/surreal-client.md#new-session) is a [`SurrealSession`](/docs/reference/kotlin/api/core/session.md) that exposes the same querying and authentication API as the client, but with isolated state.

```kotlin
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

val tenantA = client.newSession()
val tenantB = client.newSession()

tenantA.signin(buildJsonObject { put("user", "a"); put("pass", "a") })
tenantA.use("acme", "main")

tenantB.signin(buildJsonObject { put("user", "b"); put("pass", "b") })
tenantB.use("globex", "main")

// Each query runs as its own authenticated tenant, isolated from the other.
val aPeople = tenantA.query("SELECT * FROM person")
val bPeople = tenantB.query("SELECT * FROM person")
```

## Closing sessions

Close a session with [`.closeSession()`](/docs/reference/kotlin/api/core/surreal-client.md#close-session) when you no longer need it. This does not close the underlying connection.

```kotlin
client.closeSession(tenantA)
```

## Learn more

- [Session reference](/docs/reference/kotlin/api/core/session.md) for the session API
- [Authentication](/docs/reference/kotlin/concepts/authentication.md) for per-session credentials
- [Transactions](/docs/reference/kotlin/concepts/transactions.md) - transactions run within a session

---

Source: https://surrealdb.com/docs/reference/kotlin/concepts/serialization

# Serialisation

Encode and decode records using kotlinx.serialisation with the SurrealDB Kotlin SDK.

The Kotlin SDK uses [`kotlinx.serialization`](https://github.com/Kotlin/kotlinx.serialization) as its data model. Payloads are sent and received as JSON, so you work with [`JsonElement`](/docs/reference/kotlin/concepts/value-types.md) values directly, or decode them into your own [`@Serializable`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-core/kotlinx.serialization/-serializable/) types.

## Defining serializable types

Annotate your data classes with `@Serializable`. Field names map directly to record fields; use `@SerialName` to map a different key.

```kotlin
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
data class Person(
    val name: String,
    val age: Int,
    @SerialName("created_at") val createdAt: String? = null,
)
```

## Decoding query results

The inline [`.queryAs<T>()`](/docs/reference/kotlin/api/core/surreal-client.md#query-as) helper runs a query and decodes its result into `T`, while every fluent builder offers the typed [`.awaitAs<T>()`](/docs/reference/kotlin/api/core/query-builder.md#await-as) terminal.

```kotlin
import com.surrealdb.kotlin.query.Table
import com.surrealdb.kotlin.query.awaitAs

// Via raw SurrealQL
val people: List<Person> = client.queryAs("SELECT * FROM person")

// Via a builder
val sameAgain: List<Person> = client.select(Table("person")).awaitAs()
```

To decode an arbitrary [`JsonElement`](/docs/reference/kotlin/concepts/value-types.md) you already hold, use [`.decode<T>()`](/docs/reference/kotlin/api/core/surreal-client.md#decode).

```kotlin
val element = client.query("SELECT * FROM person:ada")
val ada: Person = client.decode(element)
```

## Building payloads

When writing data, build a [`JsonObject`](/docs/reference/kotlin/concepts/value-types.md) with [`buildJsonObject`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/build-json-object.html), or encode a serializable instance with the client's [`json`](/docs/reference/kotlin/api/core/surreal-client.md) instance.

```kotlin
import kotlinx.serialization.json.encodeToJsonElement

val data = client.json.encodeToJsonElement(Person("Ada", 36))
client.create(com.surrealdb.kotlin.query.Table("person")).content(data).await()
```

## Customising the JSON format

The [`json`](/docs/reference/kotlin/api/core/client-config.md#fields) field on [`SurrealClientConfig`](/docs/reference/kotlin/api/core/client-config.md) lets you supply a custom [`Json`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json/) instance, for example to register contextual serializers or change null handling. The default ignores unknown keys and is lenient.

```kotlin
import kotlinx.serialization.json.Json

val client = SurrealClient(
    SurrealClientConfig(
        url = "ws://localhost:8000",
        json = Json {
            ignoreUnknownKeys = true
            isLenient = true
            explicitNulls = false
        },
    ),
)
```

## Learn more

- [Value types](/docs/reference/kotlin/concepts/value-types.md) for `Table`, `RecordId`, and the JSON model
- [Executing queries](/docs/reference/kotlin/concepts/executing-queries.md) for `queryAs`
- [Query builder reference](/docs/reference/kotlin/api/core/query-builder.md) for `awaitAs`
- [kotlinx.serialisation](https://kotlinlang.org/docs/serialization.html) for the underlying library

---

Source: https://surrealdb.com/docs/reference/kotlin/concepts/transactions

# Transactions

Group operations into atomic transactions with the SurrealDB Kotlin SDK.

[Transactions](/docs/reference/query-language/language-primitives/transactions.md) group multiple operations so they either all succeed or all fail together. The Kotlin SDK exposes transactions as extension functions on a [session](/docs/reference/kotlin/concepts/multiple-sessions.md): a block form that commits or cancels automatically, and an explicit form for manual control.

> [!NOTE]
> Transactions require a stateful connection and are only available over the **WebSocket** transport. Check support with [`client.supports(SurrealFeature.Transactions)`](/docs/reference/kotlin/api/core/surreal-client.md#supports).

## API references

<table>
	<thead>
		<tr>
			<th scope="col">Method</th>
			<th scope="col">Description</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/transaction.md#transaction-block"><code>session.transaction { }</code></a></td>
			<td scope="row" data-label="Description">Runs a block, committing or cancelling automatically</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/transaction.md#begin-transaction"><code>session.beginTransaction()</code></a></td>
			<td scope="row" data-label="Description">Begins a transaction explicitly</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/transaction.md#commit"><code>tx.commit()</code></a></td>
			<td scope="row" data-label="Description">Commits the transaction</td>
		</tr>
		<tr>
			<td scope="row" data-label="Method"><a href="/docs/reference/kotlin/api/core/transaction.md#cancel"><code>tx.cancel()</code></a></td>
			<td scope="row" data-label="Description">Cancels the transaction</td>
		</tr>
	</tbody>
</table>

## Block form

The [`transaction { }`](/docs/reference/kotlin/api/core/transaction.md#transaction-block) builder runs your block against a [`SurrealTransaction`](/docs/reference/kotlin/api/core/transaction.md), 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](/docs/reference/kotlin/concepts/data-manipulation.md) are available scoped to it.

```kotlin
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()`](/docs/reference/kotlin/api/core/transaction.md#begin-transaction) and commit or cancel it yourself.

```kotlin
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](/docs/reference/kotlin/api/core/transaction.md) for the full API
- [Multiple sessions](/docs/reference/kotlin/concepts/multiple-sessions.md) - transactions run within a session
- [SurrealQL transactions](/docs/reference/query-language/language-primitives/transactions.md) for transaction semantics

---

Source: https://surrealdb.com/docs/reference/kotlin/concepts/value-types

# Value types

Work with record identifiers, tables, and the JSON value model in the SurrealDB Kotlin SDK.

The Kotlin SDK represents data with [`kotlinx.serialization`](/docs/reference/kotlin/concepts/serialization.md) JSON values, plus a small set of dedicated types for referring to tables and records. These are the building blocks passed to the [CRUD builders](/docs/reference/kotlin/concepts/data-manipulation.md) and queries.

## Record and table types

| Type | Description |
|---|---|
| [`Table`](/docs/reference/kotlin/api/values/table.md) | Refers to a table by name |
| [`RecordId`](/docs/reference/kotlin/api/values/record-id.md) | Refers to a single record (`table:id`) |
| [`RecordIdRange`](/docs/reference/kotlin/api/values/record-id-range.md) | Refers to a range of records within a table |

```kotlin
import com.surrealdb.kotlin.query.RecordId
import com.surrealdb.kotlin.query.Table

val table = Table("person")
val record = RecordId("person", "ada")
```

When these are bound into a query, the SDK renders them with the appropriate SurrealDB casting functions - `type::table(name)` for a [`Table`](/docs/reference/kotlin/api/values/table.md) and `type::record(table, id)` for a [`RecordId`](/docs/reference/kotlin/api/values/record-id.md) - so values are always passed safely.

## The JSON value model

Beyond the record types above, all data is modelled as [`JsonElement`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/-json-element/). Read methods return a [`JsonElement`](/docs/reference/kotlin/api/values/value.md), and write methods accept a [`JsonObject`](/docs/reference/kotlin/api/values/value.md). Build payloads with [`buildJsonObject`](https://kotlinlang.org/api/kotlinx.serialization/kotlinx-serialization-json/kotlinx.serialization.json/build-json-object.html).

```kotlin
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

val data = buildJsonObject {
    put("name", "Ada")
    put("age", 36)
}
```

> [!NOTE]
> The SDK does not ship dedicated wrapper classes for datetimes, durations, or geometries. Express these as SurrealQL literals in a query, or as the JSON values that SurrealDB expects, and decode results into your own [`@Serializable`](/docs/reference/kotlin/concepts/serialization.md) types.

## Learn more

- [`Table`](/docs/reference/kotlin/api/values/table.md), [`RecordId`](/docs/reference/kotlin/api/values/record-id.md), and [`RecordIdRange`](/docs/reference/kotlin/api/values/record-id-range.md) references
- [Value (JSON model)](/docs/reference/kotlin/api/values/value.md) reference
- [Serialisation](/docs/reference/kotlin/concepts/serialization.md) for decoding into your own types

---

Source: https://surrealdb.com/docs/reference/kotlin/installation

# Installation

The SurrealDB SDK for Kotlin is published to Maven Central and can be installed using Gradle or Maven.

The SurrealDB SDK for Kotlin is distributed through [Maven Central](https://central.sonatype.com/) under the `com.surrealdb` group. You can add it to your project using [Gradle](https://gradle.org/) or [Maven](https://maven.apache.org/).

> [!NOTE]
> The Kotlin SDK is in early development. The current version is `0.1.0-SNAPSHOT` and is **not yet published** to Maven Central. Until the first release is cut, the coordinates below are provisional, and you may need to build the SDK locally with `./gradlew publishToMavenLocal`.

## Requirements

The SDK is a [Kotlin Multiplatform](https://kotlinlang.org/docs/multiplatform.html) library built with Kotlin `2.1.x`. It supports the following targets:

| Target | Requirement |
|---|---|
| JVM | Java 11 or later |
| Android | `minSdk` 26 or later, Java 11 |
| iOS | `iosX64`, `iosArm64`, `iosSimulatorArm64` |

It depends on Kotlin Coroutines, [`kotlinx.serialization`](https://github.com/Kotlin/kotlinx.serialization), [`kotlinx.datetime`](https://github.com/Kotlin/kotlinx-datetime), and [Ktor](https://ktor.io/) for transport. Embedded (in-process) databases are intentionally not included in this release; connect to a running SurrealDB instance over WebSocket or HTTP instead.

## Install the SDK

For a Kotlin Multiplatform project, add the metadata artifact `com.surrealdb:kotlin` to your `commonMain` source set. For a single-platform project, you may instead depend on the platform-specific variant (`kotlin-jvm`, `kotlin-android`, `kotlin-iosarm64`, `kotlin-iossimulatorarm64`, or `kotlin-iosx64`).

**Gradle (Kotlin)**

```kotlin
val surrealdbVersion = "0.1.0-SNAPSHOT"

dependencies {
    implementation("com.surrealdb:kotlin:$surrealdbVersion")
}
```

**Gradle (Groovy)**

```groovy
ext {
    surrealdbVersion = "0.1.0-SNAPSHOT"
}

dependencies {
    implementation "com.surrealdb:kotlin:${surrealdbVersion}"
}
```

**Maven**

```xml
<dependency>
    <groupId>com.surrealdb</groupId>
    <artifactId>kotlin-jvm</artifactId>
    <version>0.1.0-SNAPSHOT</version>
</dependency>
```

> [!NOTE]
> Maven projects cannot resolve the Kotlin Multiplatform metadata artifact, so use a platform-specific variant such as `kotlin-jvm`.

## Import the SDK

After installing, import the client from the `com.surrealdb.kotlin` package.

```kotlin
import com.surrealdb.kotlin.SurrealClient
import com.surrealdb.kotlin.SurrealClientConfig
```

## Next steps

- [Getting started](/docs/languages/kotlin.md) for a complete working example
- [Connecting to SurrealDB](/docs/reference/kotlin/concepts/connecting-to-surrealdb.md) for connection options and protocols
- [Authentication](/docs/reference/kotlin/concepts/authentication.md) for signing in and managing credentials

---

Source: https://surrealdb.com/docs/languages/kotlin

# Kotlin quickstart

Connect to SurrealDB and run your first queries with the Kotlin SDK.

The Kotlin SDK for SurrealDB lets you connect to a database and query it from your application with coroutines. This guide covers connecting, authenticating, and running your first queries.

> [!NOTE]
> Every network operation on the SDK is a `suspend` function, so the examples below run inside a coroutine (for example, a [`runBlocking`](https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html) block or a `CoroutineScope`).

## 1. Install the SDK

Follow the [installation guide](/docs/reference/kotlin/installation.md) to add the SDK as a dependency in your project. Once installed, import the client to start using it.

```kotlin
import com.surrealdb.kotlin.SurrealClient
import com.surrealdb.kotlin.SurrealClientConfig
```

## 2. Connect to SurrealDB

Create a [`SurrealClient`](/docs/reference/kotlin/api/core/surreal-client.md) with a [`SurrealClientConfig`](/docs/reference/kotlin/api/core/client-config.md), then call [`.use()`](/docs/reference/kotlin/api/core/surreal-client.md#use) to select a namespace and database, and [`.signin()`](/docs/reference/kotlin/api/core/surreal-client.md#signin) to authenticate.

The transport is selected automatically from the URL scheme:
- **WebSocket** (`ws://`, `wss://`) for long-lived stateful connections that support live queries, transactions, and multiple sessions
- **HTTP** (`http://`, `https://`) for short-lived stateless connections

```kotlin
import com.surrealdb.kotlin.SurrealClient
import com.surrealdb.kotlin.SurrealClientConfig
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

fun main() = runBlocking {
    val client = SurrealClient(SurrealClientConfig(url = "ws://localhost:8000"))

    client.signin(buildJsonObject {
        put("user", "root")
        put("pass", "secret")
    })
    client.use("surrealdb", "docs")

    // ...

    client.close()
}
```

The client connects automatically on first use (`autoConnect` defaults to `true`). Call [`.close()`](/docs/reference/kotlin/api/core/surreal-client.md#close) when you are finished to release resources.

## 3. Inserting data into SurrealDB

To represent records in your application, define [`@Serializable`](/docs/reference/kotlin/concepts/serialization.md) data classes that match your table structure.

```kotlin
import kotlinx.serialization.Serializable

@Serializable
data class Person(val name: String, val age: Int)
```

Use the [`.create()`](/docs/reference/kotlin/api/core/surreal-client.md#create) builder to insert a record. Pass a [`Table`](/docs/reference/kotlin/api/values/table.md) to create in a table with a generated ID, or a [`RecordId`](/docs/reference/kotlin/api/values/record-id.md) to create a record with a specific ID. Builders are terminated with `await()` (raw JSON) or the typed [`awaitAs<T>()`](/docs/reference/kotlin/api/core/query-builder.md#await-as) extension.

```kotlin
import com.surrealdb.kotlin.query.RecordId
import com.surrealdb.kotlin.query.Table
import com.surrealdb.kotlin.query.awaitAs
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

val created: Person = client
    .create(RecordId("person", "john"))
    .content(buildJsonObject {
        put("name", "John")
        put("age", 32)
    })
    .awaitAs()
```

## 4. Retrieving data from SurrealDB

### Selecting records

The [`.select()`](/docs/reference/kotlin/api/core/surreal-client.md#select) builder retrieves records from a table or a single record by its [`RecordId`](/docs/reference/kotlin/api/values/record-id.md). Refine it with [`.where()`](/docs/reference/kotlin/api/core/query-builder.md) using the [expression helpers](/docs/reference/kotlin/api/core/query-builder.md#expressions).

```kotlin
import com.surrealdb.kotlin.query.Table
import com.surrealdb.kotlin.query.field
import com.surrealdb.kotlin.query.gte
import com.surrealdb.kotlin.query.awaitAs

val adults: List<Person> = client
    .select(Table("person"))
    .where(field("age") gte 18)
    .limit(50)
    .awaitAs()
```

### Running SurrealQL queries

For more advanced use cases, use [`.query()`](/docs/reference/kotlin/api/core/surreal-client.md#query) to execute [SurrealQL](/docs/reference/query-language.md) statements with bound [parameters](/docs/reference/query-language/language-primitives/parameters.md), or [`.queryAs<T>()`](/docs/reference/kotlin/api/core/surreal-client.md#query-as) to decode the result directly.

```kotlin
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put

val people: List<Person> = client.queryAs(
    "SELECT * FROM person WHERE age > \$min_age",
    buildJsonObject { put("min_age", 25) },
)
```

## 5. Closing the connection

Call [`.close()`](/docs/reference/kotlin/api/core/surreal-client.md#close) to release the connection and all associated resources.

```kotlin
client.close()
```

## Next steps

You have learned how to install the SDK, connect to SurrealDB, create records, and retrieve data. There is a lot more you can do with the SDK, including updating and deleting records, authentication, live queries, and transactions.

- [Connecting to SurrealDB](/docs/reference/kotlin/concepts/connecting-to-surrealdb.md) - Learn how to manage connections, protocols, and reconnection.

- [Authentication](/docs/reference/kotlin/concepts/authentication.md) - Read more about authentication and how to integrate it into your application.

- [Data manipulation](/docs/reference/kotlin/concepts/data-manipulation.md) - Learn how to create, read, update, and delete records using the builders.

- [API Reference](/docs/reference/kotlin/api/core/surreal-client.md) - Complete reference for the client, builders, types, and errors.

> [!NOTE]
> This getting-started guide covers the essentials. For the complete methods, API, and concept reference, see the [Kotlin SDK reference](/docs/reference/kotlin.md).
