SurrealQueryable

The SurrealQueryable class is an abstract base class that provides all query execution methods for interacting with SurrealDB. It is the foundation for executing database operations and is extended by SurrealSession and SurrealTransaction.

Extended by: SurrealSession, SurrealTransaction

Source: api/queryable.ts

Access user-defined API endpoints. This property returns a SurrealApi instance for invoking custom database APIs.

You can provide type definitions for type-safe API calls.

Type: SurrealApi<TPaths>

Examples:

Basic API Access

const api = db.api();
const result = await api.get('/users');

Type-Safe API Access

type MyPaths = {
"/users": { get: [void, User[]] };
[K: `/users/${number}`]: { get: [void, User] };
};

const api = db.api<MyPaths>();
const users = await api.get("/users"); // Type: User[]

API with Prefix

const usersApi = db.api<MyPaths>("/users");
const user = await usersApi.get("123"); // GET /users/123

Execute raw SurrealQL statements against the database.

Method Syntax

db.query<R>(query, bindings?)
db.query<R>(boundQuery)
ParameterTypeDescription
query string | BoundQueryThe SurrealQL query string or BoundQuery instance.
bindings Record<string, unknown>Variables to bind in the query (when using string query).
  • R extends unknown[] - Array of result types for each query statement

Query<R> - A query instance that can be configured and executed

Simple Query

const result = await db.query('SELECT * FROM users').collect();
console.log(result); // [{ success: true, result: [...] }]

Query with Bindings

const result = await db.query(
'SELECT * FROM users WHERE age > $age',
{ age: 18 }
).collect();

Multiple Statements

const results = await db.query<[User[], Post[]]>(`
SELECT * FROM users;
SELECT * FROM posts;
`).collect();

const [users, posts] = results.map(r => r.result);

Using BoundQuery

import { surql } from 'surrealdb';

const query = surql`SELECT * FROM users WHERE age > ${18}`;
const result = await db.query(query).collect();

Select records from the database by record ID, record ID range, or table.

Method Syntax

db.select<T>(recordId)
db.select<T>(range)
db.select<T>(table)
ParameterTypeDescription
recordId RecordIdA specific record ID to select.
range RecordIdRangeA range of record IDs to select.
table TableA table to select all records from.

SelectPromise<T> - A promise with chainable configuration methods

Select by Record ID

const user = await db.select(new RecordId('users', 'john'));

Select All from Table

const users = await db.select(new Table('users'));

Select with Configuration

const users = await db.select(new Table('users'))
.where('age > 18')
.limit(10)
.start(0);

Create new records in the database.

Method Syntax

db.create<T>(recordId)
db.create<T>(table)
ParameterTypeDescription
recordId RecordIdThe record ID for the new record.
table TableThe table to create a record in (auto-generated ID).

CreatePromise<T> - A promise with chainable configuration methods

Create with Specific ID

const user = await db.create(new RecordId('users', 'john'))
.content({ name: 'John Doe', email: 'john@example.com' });

Create with Auto-Generated ID

const user = await db.create(new Table('users'))
.content({ name: 'Jane Doe', email: 'jane@example.com' });

Insert one or multiple records into the database.

Method Syntax

db.insert<T>(data)
db.insert<T>(table, data)
ParameterTypeDescription
table TableThe table to insert records into.
data T | T[]One or more records to insert.

InsertPromise<T> - A promise with chainable configuration methods

Insert Single Record

const user = await db.insert({
id: new RecordId('users', 'alice'),
name: 'Alice',
email: 'alice@example.com'
});

Insert Multiple Records

const users = await db.insert([
{ id: new RecordId('users', 'bob'), name: 'Bob' },
{ id: new RecordId('users', 'carol'), name: 'Carol' }
]);

Insert into Table

const users = await db.insert(new Table('users'), [
{ name: 'Dave' },
{ name: 'Eve' }
]);

Update existing records in the database.

Method Syntax

db.update<T>(recordId)
db.update<T>(range)
db.update<T>(table)
ParameterTypeDescription
recordId RecordIdA specific record ID to update.
range RecordIdRangeA range of record IDs to update.
table TableA table to update all records in.

UpdatePromise<T> - A promise with chainable configuration methods

Update with Content

const user = await db.update(new RecordId('users', 'john'))
.content({ name: 'John Smith', email: 'john@example.com' });

Update with Merge

const user = await db.update(new RecordId('users', 'john'))
.merge({ email: 'newemail@example.com' });

Update with Condition

const users = await db.update(new Table('users'))
.merge({ verified: true })
.where('age > 18');

Upsert records (insert if they don't exist, replace if they do).

Method Syntax

db.upsert<T>(recordId)
db.upsert<T>(range)
db.upsert<T>(table)
ParameterTypeDescription
recordId RecordIdA specific record ID to upsert.
range RecordIdRangeA range of record IDs to upsert.
table TableA table to upsert all records in.

UpsertPromise<T> - A promise with chainable configuration methods

const user = await db.upsert(new RecordId('users', 'john'))
.content({ name: 'John Doe', email: 'john@example.com' });

Delete records from the database.

Method Syntax

db.delete<T>(recordId)
db.delete<T>(range)
db.delete<T>(table)
ParameterTypeDescription
recordId RecordIdA specific record ID to delete.
range RecordIdRangeA range of record IDs to delete.
table TableA table to delete all records from.

DeletePromise<T> - A promise with chainable configuration methods

Delete Single Record

const deleted = await db.delete(new RecordId('users', 'john'));

Delete All from Table

const deleted = await db.delete(new Table('users'));

Create graph relationships (edges) between records.

Method Syntax

db.relate<T>(from, edge, to, data?)
db.relate<T>(from[], edge, to[], data?)
ParameterTypeDescription
from RecordId | RecordId[]The source record(s) for the relationship.
edge Table | RecordIdThe edge table or specific edge record ID.
to RecordId | RecordId[]The target record(s) for the relationship.
data Partial<T>Optional data to store on the edge record.

RelatePromise<T> - A promise for the relationship operation

Create Single Relationship

const edge = await db.relate(
new RecordId('users', 'john'),
new Table('likes'),
new RecordId('posts', '1'),
{ timestamp: new Date() }
);

Create Multiple Relationships

const edges = await db.relate(
[new RecordId('users', 'john'), new RecordId('users', 'jane')],
new Table('follows'),
[new RecordId('users', 'alice'), new RecordId('users', 'bob')]
);

Create a live query subscription to receive real-time updates when records change.

Method Syntax

db.live<T>(what)
ParameterTypeDescription
what LiveResourceThe table, record ID, or range to subscribe to.

ManagedLivePromise<T> - A managed live query subscription

const subscription = await db.live(new Table('users'));

for await (const update of subscription) {
console.log('Update:', update.action, update.result);
}

Subscribe to an existing live query using its ID.

Method Syntax

db.liveOf(id)
ParameterTypeDescription
id UuidThe UUID of the existing live query.

UnmanagedLivePromise - An unmanaged live query subscription

const liveQueryId = await db.query('LIVE SELECT * FROM users').collect();
const subscription = db.liveOf(liveQueryId);

Execute a SurrealDB function or SurrealML model.

Method Syntax

db.run<T>(name, args?)
db.run<T>(name, version, args?)
ParameterTypeDescription
name stringThe full name of the function to run (e.g., "fn::calculate").
version stringThe version of a SurrealML model to use.
args unknown[]Arguments to pass to the function.

RunPromise<T> - A promise for the function result

Run Custom Function

const result = await db.run('fn::calculate', [10, 20]);

Run SurrealML Model

const prediction = await db.run('ml::predict', '1.0.0', [inputData]);

Get the currently authenticated record user by selecting the $auth parameter.

Method Syntax

db.auth<T>()

AuthPromise<T> - A promise for the authenticated user record

const user = await db.auth();
console.log('Current user:', user);

Was this page helpful?