• Start

Languages

/

Mojo

Quickstart

A complete working example that connects to SurrealDB from Mojo, runs a query, and reads the response.

This guide walks through a minimal Mojo program that connects to a local SurrealDB instance, runs a query, and reads the result. It assumes you have already installed the SDK.

Start a local SurrealDB with an in-memory store, using the CLI or Docker:

surreal start --bind 127.0.0.1:8000 --user root --pass root memory

Create a Mojo file and connect over HTTP. The access_token here is the base64 encoding of root:root, sent as HTTP Basic auth.

from surrealdb import AsyncSurrealClient, ConnectOptions
from std.collections import Optional


def main():
var client = AsyncSurrealClient()
_ = client.connect(
"http://localhost:8000/rpc",
ConnectOptions(
namespace=Optional(String("test")),
database=Optional(String("test")),
access_token=Optional(String("Basic cm9vdDpyb290")), # root:root
),
)

var resp = client.query("RETURN 1 + 1;")
if resp.is_ok():
print("result:", resp.result.value() if resp.result else "null")
else:
print("error:", resp.error_message().value())

Run it:

pixi run mojo run -I src yourfile.mojo

The client exposes convenience methods that wrap common SurrealQL statements. Each takes the table or record to act on and a JSON document.

client.create("person", '{ "name": "Chiru", "age": 30 }')
client.select("person:chiru")
client.update("person:chiru", '{ "age": 31 }')
client.delete("person:chiru")
client.insert("person", '[{ "name": "Alice" }, { "name": "Bob" }]')

Every call returns an RpcResponse. Check is_ok() before reading the result, and inspect the error fields otherwise.

var resp = client.query("SELECT * FROM person WHERE age > 18;")

if resp.is_ok():
# CBOR-decoded text representation for convenience
if resp.result:
print(resp.result.value())
# Raw CBOR bytes if you need them
print("bytes:", len(resp.result_raw))
else:
print("code:", resp.error_code().value())
print("message:", resp.error_message().value())

Was this page helpful?