• Start

API Reference

/

Core Classes

SurrealQueryable

The SurrealQueryable class provides all query execution methods for interacting with SurrealDB.

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

Create a SurrealApi instance for invoking user-defined API endpoints. You can provide type definitions for type-safe API calls and an optional path prefix.

Method Syntax
db.api<TPaths>(prefix?)

Parameter

Type

Description

prefixstring

A path prefix to prepend to all API calls made through this instance.

[`SurrealApi`](/docs/reference/javascript/api/core/surreal-api) - An API instance for invoking custom database APIs

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)

Parameter

Type

Description

query

string |

BoundQuery

The SurrealQL query string or BoundQuery instance.

bindingsRecord<string, unknown>

Variables to bind in the query (when using string query).

  • R extends unknown[] - Array of result types for each query statement

[`Query`](/docs/reference/javascript/api/queries/query) - 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)

Parameter

Type

Description

recordId

AnyRecordId

A specific record ID to select.

range

RecordIdRange

A range of record IDs to select.

table

Table

A table to select all records from.

  • For `RecordId`: [`SelectPromise`](/docs/reference/javascript/api/queries/select-promise) - A promise resolving to a single record or `undefined`

  • For `Table` or `RecordIdRange`: [`SelectPromise`](/docs/reference/javascript/api/queries/select-promise) - A promise resolving to an array of records

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)

Parameter

Type

Description

recordId

AnyRecordId

The record ID for the new record.

table

Table

The table to create a record in (auto-generated ID).

[`CreatePromise, T>`](/docs/reference/javascript/api/queries/create-promise) - 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)

Parameter

Type

Description

table

Table

The table to insert records into.

dataValues<T> | Values<T>[]

One or more records to insert.

[`InsertPromise`](/docs/reference/javascript/api/queries/insert-promise) - 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)

Parameter

Type

Description

recordId

AnyRecordId

A specific record ID to update.

range

RecordIdRange

A range of record IDs to update.

table

Table

A table to update all records in.

[`UpdatePromise`](/docs/reference/javascript/api/queries/update-promise) - 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).

Warning

This function replaces existing record data with the specified data.

Method Syntax
db.upsert<T>(recordId)
db.upsert<T>(range)
db.upsert<T>(table)

Parameter

Type

Description

recordId

AnyRecordId

A specific record ID to upsert.

range

RecordIdRange

A range of record IDs to upsert.

table

Table

A table to upsert all records in.

[`UpsertPromise`](/docs/reference/javascript/api/queries/upsert-promise) - 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)

Parameter

Type

Description

recordId

AnyRecordId

A specific record ID to delete.

range

RecordIdRange

A range of record IDs to delete.

table

Table

A table to delete all records from.

[`DeletePromise`](/docs/reference/javascript/api/queries/delete-promise) - 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?)

Parameter

Type

Description

from

AnyRecordId

| AnyRecordId[]

The source record(s) for the relationship.

edge

Table |

AnyRecordId

The edge table or specific edge record ID.

to

AnyRecordId

| AnyRecordId[]

The target record(s) for the relationship.

dataPartial<T>

Optional data to store on the edge record.

[`RelatePromise`](/docs/reference/javascript/api/queries/relate-promise) - 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)

Parameter

Type

Description

what

LiveResource

The table, record ID, or range to subscribe to.

[`ManagedLivePromise`](/docs/reference/javascript/api/queries/live-promise) - 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.

Note

This function is for use with live queries not managed by the driver.

Method Syntax
db.liveOf<T>(id)

Parameter

Type

Description

id

Uuid

The UUID of the existing live query.

[`UnmanagedLivePromise`](/docs/reference/javascript/api/queries/live-promise) - 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?)

Parameter

Type

Description

namestring

The full name of the function to run (e.g.,

"fn::calculate"

).

versionstring

The version of a SurrealML model to use.

argsunknown[]

Arguments to pass to the function.

[`RunPromise`](/docs/reference/javascript/api/queries/run-promise) - 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.

Note

The user must have permission to select their own record, otherwise an empty result is returned.

Method Syntax
db.auth<T>()

`AuthPromise` - A promise for the authenticated user record, or `undefined` if not authenticated

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

Was this page helpful?