Skip to content

API Reference

/

Core

SurrealSession

A session object runs requests in one session on the server, with its own namespace, database, variables and sign-in, over the WebSocket connection that created it. This page lists the properties and methods of BlockingSurrealSession, which a blocking connection returns, and AsyncSurrealSession, which an asynchronous connection returns. See Multiple sessions for how to use them.

Sessions need a WebSocket connection (ws:// or wss://) and SurrealDB 3.0 or later. On an HTTP or embedded connection, new_session() raises UnsupportedFeatureError. Against SurrealDB 2.x, it raises UnavailableFeatureError.

Source: async_ws.py · blocking_ws.py

Syntax
session = db.new_session()

Returns: a BlockingSurrealSession on a blocking connection, or an AsyncSurrealSession on an asynchronous connection

new_session() starts a session that is signed in as the user of the connection, with no namespace, database or variables. Two other methods start a session as a copy of an existing one: fork() on a session, and fork_session() on the connection.

from surrealdb import Surreal

db = Surreal("ws://localhost:8000")
db.connect()
db.signin({"username": "root", "password": "secret"})

session = db.new_session()
session.use("surrealdb", "reports")

The UUID of the session on the server. db.sessions() lists the same ids, and the connection methods that take a session_id keyword accept it.

The version that the server reported when the connection opened, such as "4.0.0". It is the same value as the server_version of the connection.

A session has the query, data, authentication and variable methods of the connection. Each one runs in the session, with its namespace, database, variables and sign-in. The links lead to the full description of each method in the Surreal reference.

On an AsyncSurrealSession, await each method. The methods that return a builder return one that runs when you await it.

MethodReturns on BlockingSurrealSessionDescription
.use(namespace, database)NoneSelect a namespace, a database, or both, for the session.
.query(query, vars)SyncQueryBuilderRun SurrealQL. .execute() gives one result for each statement, and .first() gives the result of the first statement.
.query_raw(query, vars)dictRun SurrealQL and return the response with the status of each statement.
.batch()BatchCollect statements to send as one transaction in one request.
.run(name, args, version)ValueCall a SurrealDB function.
.select(record, fields, into)SyncCrudBuilderSelect a record, a range of records or a table.
.create(record, data, into)The record, or a builder when called without dataCreate a record.
.update(record, data, into)The result, or a builder when called without dataReplace the content of records, or chain .merge(), .patch() or .replace().
.upsert(record, data, into)The result, or a builder when called without dataCreate or update records.
.delete(record, into)SyncCrudBuilderDelete records.
.insert(table, data, into, relation)A list of records, or a builder when called without dataInsert records. relation=True inserts relations.
.relate(from_, edge, to, data)The edge, or a builder when called without dataRelate records through an edge table.
.signin(vars)TokensSign the session in.
.signup(vars)TokensSign up a record user and sign the session in as that user.
.authenticate(token)NoneAuthenticate the session with an access token.
.refresh(tokens)TokensExchange the refresh token of the session for a new pair of tokens.
.revoke(tokens)NoneRevoke a refresh token.
.invalidate()NoneSign the session out.
.reset()NoneClear the namespace, database, variables and sign-in of the session.
.info()ValueReturn the record of the signed-in record user.
.let(key, value)NoneDefine a variable in the session.
.set(key, value)NoneAnother name for .let().
.unset(key)NoneRemove a variable from the session.
.live(table, diff)LiveSubscriptionStart a live query in the session.
.live_of(live_id)LiveSubscriptionAttach to a live query that was started some other way.
.subscribe_live(query_uuid)A generator of notificationsRead the notifications of a live query.
.kill(query_uuid)NoneStop a live query.
.api(path, method, body, headers, query)ApiResponseCall an endpoint defined with DEFINE API.
.gql(query, vars)listRun an ISO GQL query.
.graphql(query, variables, operation_name)dictRun a GraphQL query.
.filesBlockingFilesA property with helpers for files in storage buckets.
.timeout(seconds)A context managerChange how long requests in the session wait for a reply inside a with block.
.version()strAsk the server for its version.

The methods that act on the whole connection are not on a session: connect(), close(), health(), subscribe(), new_session(), fork_session(), sessions(), attach(), detach(), export(), export_to() and import_(). Call them on the connection.

Begin a transaction in the session. Needs SurrealDB 3.0 or later.

Syntax
session.begin_transaction()

Returns: a BlockingSurrealTransaction, or an AsyncSurrealTransaction on an asynchronous session

The transaction runs with the namespace, database and sign-in of the session. It is a context manager that commits when the block finishes, and cancels when the block raises an exception:

from surrealdb import RecordID

with session.begin_transaction() as txn:
    txn.create(RecordID("person", "tobie"), {"name": "Tobie"})
    txn.create(RecordID("person", "jaime"), {"name": "Jaime"})

On an asynchronous session, write async with await session.begin_transaction() as txn:.

Start a new session as a copy of this one. Needs SurrealDB 3.0 or later.

Syntax
session.fork()

Returns: a new session of the same class

The copy gets the namespace, database, variables and access token of the session. It does not get the refresh token, because the server accepts a refresh token only once. The two sessions are independent from then on.

copy = session.fork()
print(copy.query("RETURN session::db()").first())
Output
reports

On an asynchronous session, write copy = await session.fork().

End the session on the server.

Syntax
session.close_session()

Returns: None

The connection and its other sessions stay open. A request on the session object after close_session() raises NotFoundError. Sessions are not context managers, so to end a session also when your code raises an exception, call close_session() in a finally block, as the example below does.

On an asynchronous session, write await session.close_session().

The example below runs a transaction in a session that uses another database, and closes the session at the end:

from surrealdb import RecordID, Surreal

with Surreal("ws://localhost:8000") as db:
    db.signin({"username": "root", "password": "secret"})
    db.use("surrealdb", "docs")

    reports = db.new_session()
    try:
        reports.use("surrealdb", "reports")

        with reports.begin_transaction() as txn:
            for name in ("Tobie", "Jaime"):
                record = RecordID("person", name.lower())
                txn.create(record, {"name": name})

        query = "SELECT VALUE name FROM person ORDER BY name"
        print(reports.query(query).first())
        print(db.query("RETURN session::db()").first())
        print(reports.id in db.sessions())
    finally:
        reports.close_session()
Output
['Jaime', 'Tobie']
docs
True

Was this page helpful?