Skip to content

Concepts

Multiple sessions

A session holds its own authentication, namespace and database, and variables. The Go SDK can run several sessions over one WebSocket connection. This lets one program act as several users or tenants without a separate connection for each one. This page covers attaching, copying, listing, resetting and detaching sessions.

Sessions need a WebSocket connection (ws:// or wss://). On an HTTP connection, Attach, Fork and Sessions return constants.ErrSessionsNotSupported.

Method

Description

db.Attach(ctx)

Attaches a new session to the connection

db.Fork(ctx)

Attaches a session that starts as a copy of the default session

session.Fork(ctx)

Attaches a session that starts as a copy of this one

db.Sessions(ctx)

Lists the sessions attached to the connection

session.Reset(ctx)

Returns a session to the state it had when it was attached

session.Detach(ctx)

Removes the session from the server

session.ID()

Returns the UUID of the session

.Attach() attaches a new session to the connection and returns a *Session. The session starts signed out, with no namespace or database selected. Before you query, sign the session in and select a namespace and database:

session, err := db.Attach(ctx)
if err != nil {
	log.Fatal(err)
}
defer session.Detach(ctx)

if _, err := session.SignIn(ctx, surrealdb.Auth{
	Username: "root",
	Password: "secret",
}); err != nil {
	log.Fatal(err)
}

if err := session.Use(ctx, "surrealdb", "docs"); err != nil {
	log.Fatal(err)
}

Every query and CRUD function takes a *Session in place of the *DB:

people, err := surrealdb.Query[[]Person](ctx, session, "SELECT * FROM person", nil)

tobie, err := surrealdb.Select[Person](ctx, session, models.NewRecordID("person", "tobie"))

The request runs as the signed-in user of the session. It uses the namespace and database that the session selected, and the variables of the session.

Sessions do not share state with each other, or with the default session of the *DB:

  • Signing in on a session does not change who the other sessions are signed in as.

  • .Use() on a session does not change the namespace or database of the others.

  • Variables set with .Let() belong to the session that set them.

  • Live queries started on a session belong to it, and run with its permissions.

admin, err := db.Attach(ctx)
if err != nil {
	log.Fatal(err)
}
defer admin.Detach(ctx)

customer, err := db.Attach(ctx)
if err != nil {
	log.Fatal(err)
}
defer customer.Detach(ctx)

_, err = admin.SignIn(ctx, surrealdb.Auth{Username: "root", Password: "secret"})
_ = admin.Use(ctx, "shop", "main")

_, err = customer.SignIn(ctx, map[string]any{
	"NS":    "shop",
	"DB":    "main",
	"AC":    "account",
	"email": "tobie@example.com",
	"pass":  "hunter123",
})
_ = customer.Use(ctx, "shop", "main")

.Fork() attaches a new session that starts as a copy of another session. The copy has the same namespace and database and the same variables, and it is signed in with the same access token. db.Fork() copies the default session, and session.Fork() copies that session. After the copy, the two sessions are independent:

if err := db.Let(ctx, "tenant", "acme"); err != nil {
	log.Fatal(err)
}

fork, err := db.Fork(ctx)
if err != nil {
	log.Fatal(err)
}
defer fork.Detach(ctx)

tenant, err := surrealdb.Query[string](ctx, fork, "RETURN $tenant", nil)
fmt.Println((*tenant)[0].Result)
Output
acme

The server cannot copy the authentication of a session, so the fork signs in with the access token of the original. A session that signed in with a username and password can outlive that token, which lasts one hour by default. After the token expires, .Fork() attaches nothing and returns an error that wraps constants.ErrForkTokenExpired. In that case, attach a new session with .Attach(). Then sign in the new session yourself.

A fork does not copy a token pair, because a refresh token works only once. As a result, a fork does not renew its access token by itself.

.Sessions() returns the sessions attached to the connection, other than the default one:

sessions, err := db.Sessions(ctx)
if err != nil {
	log.Fatal(err)
}
for _, s := range sessions {
	fmt.Println(s.ID())
}

The list holds every other session on the connection. It also includes sessions that this client did not attach, such as a session from a direct call on the connection. The client does not know the state of such a session, so .Fork() on it returns constants.ErrForkUntracked.

.Reset() returns a session to the state it had when it was attached. The session is then signed out and has no namespace, database or variables. .Reset() also kills its live queries. The session stays attached, so it can sign in again as another user:

if err := session.Reset(ctx); err != nil {
	log.Fatal(err)
}

A session can start its own interactive transactions with .Begin(). The transaction runs as the signed-in user of the session, in the namespace and database of the session:

tx, err := session.Begin(ctx)
if err != nil {
	log.Fatal(err)
}
defer tx.Cancel(ctx)

if _, err := surrealdb.Create[any](ctx, tx, "event", map[string]any{"type": "login"}); err != nil {
	log.Fatal(err)
}

if err := tx.Commit(ctx); err != nil {
	log.Fatal(err)
}

.Detach() removes the session from the server and kills its live queries. After that, a call on the session returns constants.ErrSessionClosed:

if err := session.Detach(ctx); err != nil {
	log.Fatal(err)
}

Call defer session.Detach(ctx) directly after .Attach() or .Fork(), so that .Detach() removes the session even when a later step fails.

When the client reconnects, it attaches each session again under the same UUID. It also restores the authentication, namespace, database, variables and live queries of each session. A reconnect loses the transactions that were open in a session.

Was this page helpful?

Last updated