Connection and Authentication

Auto-generated from docstrings. For narrative usage, see the Guide.

Connection

SurrealDB.connectFunction
connect(url::String; ns=nothing, db=nothing, token=nothing, auth=nothing)
connect(f::Function, url::String; kwargs...)

Connect to a SurrealDB instance. The URL scheme determines the backend:

URL schemeBackendDescription
ws://host:portRemote WSWebSocket (stateful)
http://host:portRemote HTTPHTTP (stateless)
mem://, memory://EmbeddedIn-memory database (aliases for the same backend)
surrealkv://pathEmbeddedFile-backed database

Keyword arguments:

  • ns, db: Namespace and database to select after connecting
  • token: JWT token for authentication
  • auth: Auth struct (RootAuth, NamespaceAuth, etc.) for signin
  • reconnect::Bool=true: Auto-reconnect on socket drop (WS only)
  • reconnect_max_attempts::Int=10: Consecutive failures before giving up
  • reconnect_base_delay::Float64=0.5: Initial backoff (exponential, in seconds)
  • reconnect_max_delay::Float64=30.0: Cap on the backoff delay
  • reconnect_jitter::Float64=0.1: Random jitter factor [0,1] applied to each backoff
  • ping_interval::Float64=30.0: Keepalive cadence; 0 disables
  • tls_verify::Bool=true: Verify TLS certs on wss://. Set false only for self-signed test certs
  • rpc_timeout::Float64=30.0: Max seconds to wait for an RPC response; Inf disables
  • refresh_lead_time::Float64=30.0: How far before the access token's exp claim to fire the proactive refresh. Only active when the server issued a refresh token (WITH REFRESH scopes); otherwise no timer is scheduled.
  • wire::Symbol=:cbor: Wire format — :cbor (default, binary, type-faithful) or :json (text, legacy/debug). Selected at connect time; baked into the connection's type parameter for compile-time codec dispatch. Embedded connections ignore this parameter.
  • check_version::Bool=true: After the socket comes up, probe version() and throw UnsupportedVersionError if the server is below MINIMUM_SERVER_VERSION. Set false for development against unreleased server builds.
  • logger::AbstractSurrealLogger=NullLogger(): Synchronous observability hook for lifecycle events. Pass FnLogger to forward to a user callback. Runs on the emitting task — long-running loggers should hand off to their own task.

Returns a SurrealClient{C} where C is the concrete connection backend type.

Do-block form

The function form mirrors Base.open: the client is closed automatically on exit, even if the block throws.

SurrealDB.connect("ws://localhost:8000"; ns="test", db="test") do db
    SurrealDB.query(db, "SELECT * FROM stream")
end  # client is closed here
source
SurrealDB.close!Function
close!(client::SurrealClient)

Close the database connection. The client cannot be used after this call.

source
close!(session::SurrealSession)

Destroy the server-side session. After closing, the session must not be used. Wraps detach!.

source
SurrealDB.statusFunction
status(client::SurrealClient)

Return the current connection status as a ConnectionStatus: STATUS_CONNECTED, STATUS_DISCONNECTED, STATUS_CONNECTING, STATUS_RECONNECTING

source
SurrealDB.eventsFunction
events(client::SurrealClient{<:AbstractRemoteConnection}) -> Channel{LifecycleEvent}

Return a Channel that emits LifecycleEvent values on remote-connection state transitions. Each event carries:

  • ev.statusSTATUS_CONNECTING / STATUS_CONNECTED / STATUS_RECONNECTING / STATUS_DISCONNECTED
  • ev.attempt — 0 on first connect, N (1-based) on the Nth reconnect attempt
  • ev.cause — the Exception that triggered RECONNECTING / DISCONNECTED, or nothing
  • ev.timestamptime() at emission

Drop-in equivalent of the JS SDK's db.subscribe('connected', ...) pattern (consume ev.status for the bare ConnectionStatus). Best-effort emission — if no consumer drains the channel, events are queued (capacity

  1. and dropped silently when the buffer is full.

For synchronous side effects (e.g. structured logging), see AbstractSurrealLogger / FnLogger — those fire on the emitting task rather than buffering through the channel.

Examples

db = SurrealDB.connect("ws://localhost:8000")
@async for ev in SurrealDB.events(db)
    @info "SurrealDB lifecycle" status=ev.status attempt=ev.attempt cause=ev.cause
end
source
SurrealDB.SurrealClientType
SurrealClient{C<:AbstractConnection}

The main client type for interacting with a SurrealDB database.

Generic over the connection backend type C. Create via connect.

Examples

db = SurrealDB.connect("ws://localhost:8000")
SurrealDB.use!(db, "test", "test")
result = SurrealDB.query(db, "SELECT * FROM stream")
source
SurrealDB.AbstractRemoteConnectionType
AbstractRemoteConnection <: AbstractConnection

Common supertype for remote-server backends (RemoteWSConnection and RemoteHTTPConnection). Methods that work over either transport (query, create, select, etc.) dispatch on this; transport-specific methods (live queries, sessions, pinger) dispatch on the concrete type so HTTP-only restrictions surface as MethodError at the API boundary instead of runtime ConnectionError.

source
SurrealDB.RemoteConnectionType
RemoteConnection(url)

A remote connection to a SurrealDB server via WebSocket or HTTP.

URL schemes accepted:

  • ws://host:port / wss://host:port — WebSocket (primary, stateful)
  • http://host:port / https://host:port — HTTP (stateless)
source
SurrealDB.RemoteWSConnectionType
RemoteWSConnection = RemoteConnection{:ws}

Alias for the WebSocket transport. UnionAll wildcard over the wire-format parameter W, so it matches both RemoteConnection{:ws, :json} and RemoteConnection{:ws, :cbor}. Methods that care only about the transport dispatch on this alias; methods that care about the wire add a W parameter (see src/wire.jl).

source
SurrealDB.RemoteHTTPConnectionType
RemoteHTTPConnection = RemoteConnection{:http}

Alias for the HTTP transport. UnionAll wildcard over the wire-format parameter W, so it matches both RemoteConnection{:http, :json} and RemoteConnection{:http, :cbor}. HTTP is stateless per-request; live queries and sessions are WS-only and surface as MethodError when attempted on this type.

source
SurrealDB.Embedded.EmbeddedConnectionType
EmbeddedConnection(url)

An embedded SurrealDB connection running in-process via libsurreal.

URL schemes:

  • mem:// or memory:// — in-memory database (no persistence)
  • surrealkv://path/to/data.skv — file-backed database

surrealkv+versioned:// (MVCC mode) and rocksdb:// are not enabled in the bundled libsurreal_c build; passing them raises EmbeddedFFIError(sr_connect).

Requires libsurreal to be loaded via libsurreal_load!.

source

Connection lifecycle and observability

SurrealDB.ConnectionStatusType
ConnectionStatus

Connection lifecycle states. Held on the RemoteConnection.status field and surfaced via the events channel and status.

Values:

  • STATUS_DISCONNECTED: no active session (initial state, or after close!).
  • STATUS_CONNECTING: first-ever connect attempt in progress.
  • STATUS_CONNECTED: session established; RPCs can flow.
  • STATUS_RECONNECTING: lost session, reconnect loop attempting recovery.
source
SurrealDB.STATUS_DISCONNECTEDConstant
STATUS_DISCONNECTED

No active session. Initial state on RemoteConnection construction and terminal state after close!. No RPCs may be sent in this state; attempting to do so throws ConnectionUnavailableError. The reconnect loop only fires from STATUS_RECONNECTING; transitioning into STATUS_DISCONNECTED is final unless the user re-calls connect.

source
SurrealDB.STATUS_CONNECTINGConstant
STATUS_CONNECTING

First-ever connect attempt in progress. Emitted once at the start of connect, before the WebSocket upgrade or HTTP probe completes. Distinct from STATUS_RECONNECTING so observers can tell a cold start apart from mid-session recovery. RPCs submitted in this window block on the response channel and proceed when the transition to STATUS_CONNECTED lands.

source
SurrealDB.STATUS_CONNECTEDConstant
STATUS_CONNECTED

Session established, transport handshake complete, RPCs flow. The only state in which query / CRUD / live and friends will write to the socket without blocking on a state transition. Emitted on initial connect AND on every successful reconnect after state replay (use! / signin! / let! / live re-registrations) completes — so event consumers always see a fully-restored session.

source
SurrealDB.STATUS_RECONNECTINGConstant
STATUS_RECONNECTING

Session lost mid-operation; reconnect loop attempting recovery. Entered when the WS reader sees EOF / an IOError or the writer fails to flush. In-flight RPCs at the moment of drop receive ConnectionError via _signal_inflight_disconnect!; new RPCs submitted during this window queue on their response channels and the loop signals them on success or after reconnect_max_attempts exhausts (transition to STATUS_DISCONNECTED). The accompanying LifecycleEvent carries attempt (1-based) and cause (the triggering exception).

source
SurrealDB.LifecycleEventType
LifecycleEvent

Structured payload emitted on the events channel per connection state transition. Carries the transition target status plus reconnect diagnostics so operators can reason about reconnect storms without scraping ad-hoc @warn lines.

Fields:

  • status::ConnectionStatus — the state being transitioned INTO.
  • attempt::Int0 on first connect; reconnect attempt N (1-based) thereafter.
  • cause::Union{Exception, Nothing} — the error that triggered STATUS_RECONNECTING / STATUS_DISCONNECTED, if any.
  • timestamp::Float64time() at emission, for relative duration measurements.
source
SurrealDB.AbstractSurrealLoggerType
AbstractSurrealLogger

Supertype for observability hooks invoked synchronously on each LifecycleEvent emission. Pass via connect(...; logger=...). Concrete implementations: NullLogger (default, no-op), FnLogger (forwards to a user function).

The logger callback runs on the calling task (the reconnect loop or the connect entry path). Long-running loggers should hand off to their own task; the emit path catches exceptions and warns instead of propagating.

source

Server version bounds

SurrealDB.MAXIMUM_SERVER_VERSIONConstant
MAXIMUM_SERVER_VERSION

Upper bound (exclusive) for the supported server-version range, or nothing to disable the cap. Pinned to mark untested territory — servers at or above this version are likely to ship wire-format changes the SDK hasn't seen. Bump after live-server shakedown against the next major.

source

Authentication

SurrealDB.signin!Function
signin!(client, auth) -> token::String

Authenticate with the SurrealDB server.

auth can be:

  • RootAuth - root-level credentials
  • NamespaceAuth - namespace-level credentials
  • ScopedAuth - record-level credentials via an access method
  • Dict{String, Any} - raw parameters (e.g., for bearer keys, refresh tokens)

Returns the JWT token string on success. The SDK stores the token on the client so subsequent RPCs are authenticated automatically; the token is also replayed on reconnect.

Examples

token = SurrealDB.signin!(db, SurrealDB.RootAuth("root", "password"))

token = SurrealDB.signin!(db, SurrealDB.NamespaceAuth("ns", "db", "user", "pass"))

token = SurrealDB.signin!(db, SurrealDB.ScopedAuth("ns", "db", "access", "user", "pass"))

token = SurrealDB.signin!(db, Dict("NS" => "ns", "DB" => "db", "AC" => "access",
                                    "user" => "u", "pass" => "p"))
source
SurrealDB.signup!Function
signup!(client, auth::ScopedAuth)

Register a new user via a RECORD-scope access method.

Returns the JWT token string on success.

Note: SurrealDB signup is only available with RECORD-scoped access methods.

source
SurrealDB.authenticate!Function
authenticate!(client, token::String)

Authenticate the current connection with a pre-obtained JWT token.

This is useful when you have a JWT from a previous signin or an external auth system.

Examples

SurrealDB.authenticate!(db, "eyJ0eXAiOiJKV1QiLCJh...")
source
SurrealDB.invalidate!Function
invalidate!(client)

Clear the current authentication session. Subsequent operations will be unauthenticated.

source
SurrealDB.refresh!Function
refresh!(client) -> token::String

Exchange the current refresh token for a new access + refresh pair via the SurrealDB refresh RPC. Updates client.tokens and client.token on success and reschedules the proactive refresh timer against the new exp claim. Returns the new access token.

Throws NotAllowedError if the client has no refresh token to spend (Root/NS auth, scopes without WITH REFRESH, or after invalidate!).

source
SurrealDB.tokensFunction
tokens(client::SurrealClient) -> Union{Tokens, Nothing}

Return the typed access+refresh pair from the most recent successful sign-in, or nothing if the client is unauthenticated or the auth mode did not issue a refresh token. See Tokens.

source
SurrealDB.TokensType
Tokens(access::String, refresh::Union{String, Nothing})

Typed pair of tokens returned by SurrealDB sign-in flows that opted into WITH REFRESH on the access method. access is the short-lived JWT used for authenticated RPCs; refresh is the longer-lived token exchanged via the refresh RPC for a new access token. refresh is nothing when the auth mode doesn't issue one (Root/Namespace/legacy Scope).

source
SurrealDB.ScopedAuthType
ScopedAuth(namespace, database, access, username, password)
ScopedAuth(namespace, database, access, params::AbstractDict)

Scoped authentication credentials (record-level auth via an access method).

The 5-arg form is the convenience case for SIGNIN clauses that reference $user / $pass. The dict form passes through arbitrary keys for SIGNIN clauses referencing other params ($email, $name, etc.).

SurrealDB.signin!(db, SurrealDB.ScopedAuth("ns", "db", "user_access", "alice", "hunter2"))
SurrealDB.signin!(db, SurrealDB.ScopedAuth("ns", "db", "user_access",
                                            Dict("email" => "a@example.com",
                                                 "pass"  => "hunter2")))
source

Database scope

SurrealDB.use!Function
use!(client::SurrealClient, ns::String, db::String)

Select a namespace and database for all subsequent operations.

source
SurrealDB.infoFunction
info(client::SurrealClient)

Retrieve database-level information such as tables and schema.

Returns a Dict{String, Any}.

source
SurrealDB.versionFunction
version(client::SurrealClient)

Retrieve the SurrealDB server version.

Returns a NamedTuple with fields :version, :build, :timestamp.

source
SurrealDB.healthFunction
health(client::SurrealClient)

Check the health of the database connection.

Returns true if the database is healthy.

source

Embedded mode

SurrealDB.Embedded.libsurreal_load!Function
libsurreal_load!(path::String="")

Load the libsurreal shared library at path for embedded mode. When path is empty, falls back to the SURREALDB_LIB environment variable.

Must be called before connect("mem://") or connect("surrealkv://..."). Remote connections (ws://, http://) don't need this.

Examples

SurrealDB.libsurreal_load!("/path/to/libsurrealdb_c.dylib")
db = SurrealDB.connect("mem://")
source