blessing_surreal

A SurrealDB client for Gleam. It talks to the SurrealDB RPC protocol over WebSocket, with JSON messages.

This package is not from SurrealDB Ltd, and they do not support it.

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(names) =
  surreal.query_one(db, "SELECT VALUE name FROM user", [], decode.list(decode.string))

If the WebSocket closes, the connection opens it again. It then signs in again, selects the database again, and starts each live query again.

Types

pub type Action {
  Create
  Update
  Delete
  OtherAction(String)
}

Constructors

  • Create
  • Update
  • Delete
  • OtherAction(String)

    An action that this version of the package does not know.

A connection to SurrealDB. It stays valid when the WebSocket closes and opens again.

pub opaque type Connection
pub type Credentials {
  Root(user: String, pass: String)
  Database(
    namespace: String,
    database: String,
    user: String,
    pass: String,
  )
  Record(
    namespace: String,
    database: String,
    access: String,
    variables: List(#(String, json.Json)),
  )
}

Constructors

  • Root(user: String, pass: String)

    A root user, as surreal start --user --pass makes.

  • Database(
      namespace: String,
      database: String,
      user: String,
      pass: String,
    )

    A system user of one database, as DEFINE USER ... ON DATABASE makes. Its role (VIEWER, EDITOR, or OWNER) limits what it can do.

  • Record(
      namespace: String,
      database: String,
      access: String,
      variables: List(#(String, json.Json)),
    )

    A record user, through a DEFINE ACCESS ... TYPE RECORD with SIGNIN.

pub type Error {
  ConnectFailed(reason: String)
  Timeout
  Closed
  RpcError(code: Int, message: String)
  StatementError(index: Int, message: String)
  UnexpectedResponse(errors: List(decode.DecodeError))
}

Constructors

  • ConnectFailed(reason: String)

    The URL is wrong, or the first WebSocket handshake failed.

  • Timeout

    No answer came within the timeout of the connection.

  • Closed

    The WebSocket is closed now. The connection tries to open it again, so a later call can work.

  • RpcError(code: Int, message: String)

    SurrealDB refused the call, for example wrong credentials.

  • StatementError(index: Int, message: String)

    One statement of a query failed. index starts at 0.

  • UnexpectedResponse(errors: List(decode.DecodeError))

    The answer did not have the expected shape.

Messages to the connection actor.

pub opaque type Message

A message from a live query. live_id is the id that live returned. It stays the same after a reconnect.

pub type Notification {
  Change(
    live_id: String,
    action: Action,
    record: RecordId,
    result: dynamic.Dynamic,
  )
  Resumed(live_id: String)
}

Constructors

  • Change(
      live_id: String,
      action: Action,
      record: RecordId,
      result: dynamic.Dynamic,
    )

    A row changed.

  • Resumed(live_id: String)

    The WebSocket opened again, and the live query runs again. Changes while the WebSocket was closed are lost, so read the data again.

A record id, for example user:hafidz.

pub type RecordId {
  RecordId(table: String, key: String)
}

Constructors

  • RecordId(table: String, key: String)

Values

pub fn authenticate(
  conn: Connection,
  token: String,
) -> Result(Nil, Error)

Use a token (a JWT) for this connection. Your server can sign one for a user with the key of a DEFINE ACCESS ... TYPE RECORD WITH JWT. Then the table permissions apply to this connection. After a reconnect, the connection uses the same token again, so it must not have expired.

pub fn close(conn: Connection) -> Nil

Close the connection. It does not open again.

pub fn connect(
  url: String,
  timeout: Int,
) -> Result(Connection, Error)

Open a connection, for example to ws://localhost:8000/rpc. The timeout in milliseconds is for each handshake and each call. If the first handshake fails, this returns ConnectFailed.

pub fn datetime() -> decode.Decoder(timestamp.Timestamp)

Decode a datetime, which JSON sends as RFC 3339 text.

pub fn kill(
  conn: Connection,
  live_id: String,
) -> Result(Nil, Error)

Stop a live query.

pub fn live(
  conn: Connection,
  sql: String,
  variables: List(#(String, json.Json)),
  subscriber: process.Subject(Notification),
) -> Result(String, Error)

Start a live query, for example LIVE SELECT * FROM txn. Each change goes to subscriber. Returns the live query id for kill. SurrealDB v4 refuses a live query on a table that does not exist.

pub fn parse_record_id(text: String) -> Result(RecordId, Nil)

Split table:key. SurrealDB puts a key with special characters between backticks or ⟨ ⟩, and this removes them.

pub fn query(
  conn: Connection,
  sql: String,
  variables: List(#(String, json.Json)),
) -> Result(List(dynamic.Dynamic), Error)

Run SurrealQL. Returns the result of each statement, in order. If a statement fails, the error names it. In a failed transaction, the error names the statement that caused the failure.

Variables are JSON. A JSON string never becomes a record id, so write type::record($id) in the query when a variable holds one.

pub fn query_one(
  conn: Connection,
  sql: String,
  variables: List(#(String, json.Json)),
  decoder: decode.Decoder(a),
) -> Result(a, Error)

Run SurrealQL and decode the result of the last statement.

pub fn record_id() -> decode.Decoder(RecordId)

Decode a record id, which JSON sends as text like user:hafidz.

pub fn select_database(
  conn: Connection,
  namespace: String,
  database: String,
) -> Result(Nil, Error)

Select the namespace and the database for the next queries.

pub fn signin(
  conn: Connection,
  credentials: Credentials,
) -> Result(String, Error)

Sign in. Returns the token that SurrealDB gives for the session. After a reconnect, the connection signs in again with the same credentials.

✨ Search Document