blessing_surreal

A SurrealDB client for Gleam. It talks to the SurrealDB RPC protocol over WebSocket.

This package is not from SurrealDB Ltd, and they do not support it. "SurrealDB" is their name for their database.

Status: early (0.1.0). It works with SurrealDB v4.0.1. The JSON format is the only format now.

Install

gleam add blessing_surreal

Use

import blessing_surreal as surreal
import gleam/dynamic/decode
import gleam/json

pub fn main() {
  let assert Ok(db) = surreal.connect("ws://localhost:8000/rpc", 5000)
  let assert Ok(_) = surreal.signin(db, surreal.Root("root", "root"))
  let assert Ok(_) = surreal.select_database(db, "main", "main")

  let assert Ok(amounts) =
    surreal.query_one(
      db,
      "SELECT VALUE amount FROM txn WHERE category = $c",
      [#("c", json.string("food"))],
      decode.list(decode.int),
    )
}

Live queries

live sends each change to a Gleam Subject. One process can forward the changes to a browser.

let changes = process.new_subject()
let assert Ok(live_id) = surreal.live(db, "LIVE SELECT * FROM txn", [], changes)
case process.receive(changes, 5000) {
  Ok(surreal.Change(action:, record:, result:, ..)) -> todo as "use the change"
  Ok(surreal.Resumed(..)) -> todo as "read the data again"
  Error(Nil) -> todo as "no change in 5 seconds"
}
let assert Ok(_) = surreal.kill(db, live_id)

SurrealDB v4 refuses LIVE SELECT on a table that does not exist. Define the table first.

Reconnect

If the WebSocket closes, the connection opens it again. It waits 100 ms, then twice as long each time, up to 5 seconds. Then it signs in again, selects the database again, and starts each live query again.

Access for each user

Your server can sign a JWT for a user with the key of a DEFINE ACCESS ... TYPE RECORD WITH JWT. Call authenticate with it. Then SurrealDB applies the table permissions, for example WHERE owner = $auth.id, to that connection.

Limits of the JSON format

A later version adds CBOR, which keeps these types.

Tests

The tests need SurrealDB on port 8200. You need mise and Docker. The reconnect tests stop and restart the container with docker compose, so run them from the project root.

mise install
docker compose up -d
gleam test

Credits

License

MIT. See LICENSE.