What is session context?
A session stores information about the current connection, including:
The active namespace
The active database
Session metadata
This context is automatically used by all queries.
Switching context with USE
You can change the current namespace and database using the USE statement:
USE NS my_namespace DB my_database;After running this, all queries will operate within that context.
The name main is used as the default name for the current namespace and database when starting SurrealDB.
Parameters
As parameters are set on the connection level, setting a parameter name to a value is one way to persist a value across different namespaces and databases.
In the following example, person:one is allowed to be created inside a different namespace and database as that record ID does not yet exist inside other_ns/other_db. The $person parameter is what enabled the person:one value to be reused.
LET $person = CREATE ONLY person:one;
USE NS other_ns DB other_db;
CREATE $person;Beyond this, the only way to persist values beyond the current session is to use an SDK or an extension.
Accessing session information
You can access session details using session::* functions.
-- Current namespace
session::ns();
-- Current database
session::db();
-- Session ID
RETURN session::id();Using session context in queries
You can use session information inside queries:
IF session::db() != "production" {
THROW "This query must run in the production database";
};
-- Debugging session state
{
namespace: session::ns(),
database: session::db(),
session: session::id()
};