Connection and Authentication
Auto-generated from docstrings. For narrative usage, see the Guide.
Connection
SurrealDB.connect — Function
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 scheme | Backend | Description |
|---|---|---|
ws://host:port | Remote WS | WebSocket (stateful) |
http://host:port | Remote HTTP | HTTP (stateless) |
mem://, memory:// | Embedded | In-memory database (aliases for the same backend) |
surrealkv://path | Embedded | File-backed database |
Keyword arguments:
ns,db: Namespace and database to select after connectingtoken: JWT token for authenticationauth: Auth struct (RootAuth,NamespaceAuth, etc.) for signinreconnect::Bool=true: Auto-reconnect on socket drop (WS only)reconnect_max_attempts::Int=10: Consecutive failures before giving upreconnect_base_delay::Float64=0.5: Initial backoff (exponential, in seconds)reconnect_max_delay::Float64=30.0: Cap on the backoff delayreconnect_jitter::Float64=0.1: Random jitter factor [0,1] applied to each backoffping_interval::Float64=30.0: Keepalive cadence;0disablestls_verify::Bool=true: Verify TLS certs onwss://. Setfalseonly for self-signed test certsrpc_timeout::Float64=30.0: Max seconds to wait for an RPC response;Infdisablesrefresh_lead_time::Float64=30.0: How far before the access token'sexpclaim to fire the proactive refresh. Only active when the server issued a refresh token (WITH REFRESHscopes); 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, probeversion()and throwUnsupportedVersionErrorif the server is belowMINIMUM_SERVER_VERSION. Setfalsefor development against unreleased server builds.logger::AbstractSurrealLogger=NullLogger(): Synchronous observability hook for lifecycle events. PassFnLoggerto 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 hereSurrealDB.close! — Function
close!(client::SurrealClient)Close the database connection. The client cannot be used after this call.
close!(session::SurrealSession)Destroy the server-side session. After closing, the session must not be used. Wraps detach!.
SurrealDB.status — Function
status(client::SurrealClient)Return the current connection status as a ConnectionStatus: STATUS_CONNECTED, STATUS_DISCONNECTED, STATUS_CONNECTING, STATUS_RECONNECTING
SurrealDB.events — Function
events(client::SurrealClient{<:AbstractRemoteConnection}) -> Channel{LifecycleEvent}Return a Channel that emits LifecycleEvent values on remote-connection state transitions. Each event carries:
ev.status—STATUS_CONNECTING/STATUS_CONNECTED/STATUS_RECONNECTING/STATUS_DISCONNECTEDev.attempt— 0 on first connect, N (1-based) on the Nth reconnect attemptev.cause— theExceptionthat triggered RECONNECTING / DISCONNECTED, ornothingev.timestamp—time()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
- 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
endSurrealDB.SurrealClient — Type
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")SurrealDB.AbstractConnection — Type
AbstractConnectionAbstract base type for SurrealDB connection backends. Concrete implementations: RemoteWSConnection, RemoteHTTPConnection (both <: AbstractRemoteConnection), and EmbeddedConnection (in SurrealDB.Embedded).
SurrealDB.AbstractRemoteConnection — Type
AbstractRemoteConnection <: AbstractConnectionCommon 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.
SurrealDB.RemoteConnection — Type
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)
SurrealDB.RemoteWSConnection — Type
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).
SurrealDB.RemoteHTTPConnection — Type
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.
SurrealDB.Embedded.EmbeddedConnection — Type
EmbeddedConnection(url)An embedded SurrealDB connection running in-process via libsurreal.
URL schemes:
mem://ormemory://— 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!.
Connection lifecycle and observability
SurrealDB.ConnectionStatus — Type
ConnectionStatusConnection 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 afterclose!).STATUS_CONNECTING: first-ever connect attempt in progress.STATUS_CONNECTED: session established; RPCs can flow.STATUS_RECONNECTING: lost session, reconnect loop attempting recovery.
SurrealDB.STATUS_DISCONNECTED — Constant
STATUS_DISCONNECTEDNo 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.
SurrealDB.STATUS_CONNECTING — Constant
STATUS_CONNECTINGFirst-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.
SurrealDB.STATUS_CONNECTED — Constant
STATUS_CONNECTEDSession 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.
SurrealDB.STATUS_RECONNECTING — Constant
STATUS_RECONNECTINGSession 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).
SurrealDB.LifecycleEvent — Type
LifecycleEventStructured 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::Int—0on first connect; reconnect attempt N (1-based) thereafter.cause::Union{Exception, Nothing}— the error that triggeredSTATUS_RECONNECTING/STATUS_DISCONNECTED, if any.timestamp::Float64—time()at emission, for relative duration measurements.
SurrealDB.AbstractSurrealLogger — Type
AbstractSurrealLoggerSupertype 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.
SurrealDB.NullLogger — Type
NullLogger()Default no-op AbstractSurrealLogger. Drops every event.
SurrealDB.FnLogger — Type
FnLogger(fn)Forwards each LifecycleEvent to a user-supplied function fn(event::LifecycleEvent) -> nothing. Invoked synchronously on the calling task — see AbstractSurrealLogger.
Server version bounds
SurrealDB.MINIMUM_SERVER_VERSION — Constant
MINIMUM_SERVER_VERSIONLowest SurrealDB server version this SDK has been tested against. Connect-time version probes throw UnsupportedVersionError below this; bypass with connect(...; check_version=false).
SurrealDB.MAXIMUM_SERVER_VERSION — Constant
MAXIMUM_SERVER_VERSIONUpper 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.
Authentication
SurrealDB.signin! — Function
signin!(client, auth) -> token::StringAuthenticate with the SurrealDB server.
auth can be:
RootAuth- root-level credentialsNamespaceAuth- namespace-level credentialsScopedAuth- record-level credentials via an access methodDict{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"))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.
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...")SurrealDB.invalidate! — Function
invalidate!(client)Clear the current authentication session. Subsequent operations will be unauthenticated.
SurrealDB.refresh! — Function
refresh!(client) -> token::StringExchange 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!).
SurrealDB.tokens — Function
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.
SurrealDB.Tokens — Type
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).
SurrealDB.RootAuth — Type
RootAuth(username, password)Root-level authentication credentials.
SurrealDB.NamespaceAuth — Type
NamespaceAuth(namespace, database, username, password)Namespace-level authentication credentials.
SurrealDB.ScopedAuth — Type
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")))SurrealDB.JwtAuth — Type
JwtAuth(token)JWT token-based authentication. Use with authenticate!.
Database scope
SurrealDB.use! — Function
use!(client::SurrealClient, ns::String, db::String)Select a namespace and database for all subsequent operations.
SurrealDB.info — Function
info(client::SurrealClient)Retrieve database-level information such as tables and schema.
Returns a Dict{String, Any}.
SurrealDB.version — Function
version(client::SurrealClient)Retrieve the SurrealDB server version.
Returns a NamedTuple with fields :version, :build, :timestamp.
SurrealDB.health — Function
health(client::SurrealClient)Check the health of the database connection.
Returns true if the database is healthy.
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://")