• Start

Languages

/

Kotlin

/

Concepts

Executing queries

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

The .query() family runs raw SurrealQL and is the foundation of the SDK — the CRUD builders compile to SurrealQL and dispatch through it. Queries can be supplied as a string with a JsonObject of bound parameters, or built with the surql DSL.

MethodDescription
client.query(sql, vars)Runs SurrealQL and returns the raw result
client.queryAs<T>(sql, vars)Runs SurrealQL and decodes the result to T
client.queryResult(sql, vars)Runs SurrealQL and returns a Result
client.let(key, value)Defines a session parameter
client.unset(key)Removes a session parameter

Pass SurrealQL and, optionally, a JsonObject of bound parameters. The result is returned as a JsonElement.

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) },
)

To decode a query result straight into your own types, use the inline .queryAs<T>() helper with a @Serializable type.

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 yourself with .decode<T>().

Every networked call has a ...Result companion that returns a Result instead of throwing, which is useful when you prefer to handle failures functionally.

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

See Error handling for the exception hierarchy thrown by the non-Result variants.

Define parameters that persist for the session with .let(), and remove them with .unset(). These are referenced as $name in subsequent queries.

import kotlinx.serialization.json.JsonPrimitive

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

The surql DSL builds a parameterised BoundQuery with automatic binding of values and record identifiers.

import com.surrealdb.kotlin.query.surql

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

Was this page helpful?