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
Properties
api
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");
API with Prefix
const usersApi = db.api<MyPaths>("/users");
const user = await usersApi.get("123");
Query Methods
.query()
Execute raw SurrealQL statements against the database.
Method Syntax
db.query<R>(query, bindings?)
db.query<R>(boundQuery)
Parameters
| Parameter | Type | Description |
|---|
query required | string | BoundQuery | The SurrealQL query string or BoundQuery instance. |
bindings optional | Record<string, unknown> | Variables to bind in the query (when using string query). |
Type Parameters
R extends unknown[] - Array of result types for each query statement
Returns
Query<R> - A query instance that can be configured and executed
Examples
Simple Query
const result = await db.query('SELECT * FROM users').collect();
console.log(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()
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)
Parameters
| Parameter | Type | Description |
|---|
recordId required | RecordId | A specific record ID to select. |
range required | RecordIdRange | A range of record IDs to select. |
table required | Table | A table to select all records from. |
Returns
SelectPromise<T> - A promise with chainable configuration methods
Examples
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()
Create new records in the database.
Method Syntax
db.create<T>(recordId)
db.create<T>(table)
Parameters
| Parameter | Type | Description |
|---|
recordId required | RecordId | The record ID for the new record. |
table required | Table | The table to create a record in (auto-generated ID). |
Returns
CreatePromise<T> - A promise with chainable configuration methods
Examples
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()
Insert one or multiple records into the database.
Method Syntax
db.insert<T>(data)
db.insert<T>(table, data)
Parameters
| Parameter | Type | Description |
|---|
table optional | Table | The table to insert records into. |
data required | T | T[] | One or more records to insert. |
Returns
InsertPromise<T> - A promise with chainable configuration methods
Examples
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()
Update existing records in the database.
Method Syntax
db.update<T>(recordId)
db.update<T>(range)
db.update<T>(table)
Parameters
| Parameter | Type | Description |
|---|
recordId required | RecordId | A specific record ID to update. |
range required | RecordIdRange | A range of record IDs to update. |
table required | Table | A table to update all records in. |
Returns
UpdatePromise<T> - A promise with chainable configuration methods
Examples
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()
Upsert records (insert if they don’t exist, replace if they do).
This function replaces existing record data with the specified data.
Method Syntax
db.upsert<T>(recordId)
db.upsert<T>(range)
db.upsert<T>(table)
Parameters
| Parameter | Type | Description |
|---|
recordId required | RecordId | A specific record ID to upsert. |
range required | RecordIdRange | A range of record IDs to upsert. |
table required | Table | A table to upsert all records in. |
Returns
UpsertPromise<T> - A promise with chainable configuration methods
Example
const user = await db.upsert(new RecordId('users', 'john'))
.content({ name: 'John Doe', email: 'john@example.com' });
.delete()
Delete records from the database.
Method Syntax
db.delete<T>(recordId)
db.delete<T>(range)
db.delete<T>(table)
Parameters
| Parameter | Type | Description |
|---|
recordId required | RecordId | A specific record ID to delete. |
range required | RecordIdRange | A range of record IDs to delete. |
table required | Table | A table to delete all records from. |
Returns
DeletePromise<T> - A promise with chainable configuration methods
Examples
Delete Single Record
const deleted = await db.delete(new RecordId('users', 'john'));
Delete All from Table
const deleted = await db.delete(new Table('users'));
.relate()
Create graph relationships (edges) between records.
Method Syntax
db.relate<T>(from, edge, to, data?)
db.relate<T>(from[], edge, to[], data?)
Parameters
| Parameter | Type | Description |
|---|
from required | RecordId | RecordId[] | The source record(s) for the relationship. |
edge required | Table | RecordId | The edge table or specific edge record ID. |
to required | RecordId | RecordId[] | The target record(s) for the relationship. |
data optional | Partial<T> | Optional data to store on the edge record. |
Returns
RelatePromise<T> - A promise for the relationship operation
Examples
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')]
);
.live()
Create a live query subscription to receive real-time updates when records change.
Method Syntax
db.live<T>(what)
Parameters
| Parameter | Type | Description |
|---|
what required | LiveResource | The table, record ID, or range to subscribe to. |
Returns
ManagedLivePromise<T> - A managed live query subscription
Example
const subscription = await db.live(new Table('users'));
for await (const update of subscription) {
console.log('Update:', update.action, update.result);
}
.liveOf()
Subscribe to an existing live query using its ID.
This function is for use with live queries not managed by the driver.
Method Syntax
db.liveOf(id)
Parameters
| Parameter | Type | Description |
|---|
id required | Uuid | The UUID of the existing live query. |
Returns
UnmanagedLivePromise - An unmanaged live query subscription
Example
const liveQueryId = await db.query('LIVE SELECT * FROM users').collect();
const subscription = db.liveOf(liveQueryId);
.run()
Execute a SurrealDB function or SurrealML model.
Method Syntax
db.run<T>(name, args?)
db.run<T>(name, version, args?)
Parameters
| Parameter | Type | Description |
|---|
name required | string | The full name of the function to run (e.g., “fn::calculate”). |
version optional | string | The version of a SurrealML model to use. |
args optional | unknown[] | Arguments to pass to the function. |
Returns
RunPromise<T> - A promise for the function result
Examples
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]);
.auth()
Get the currently authenticated record user by selecting the $auth parameter.
The user must have permission to select their own record, otherwise an empty result is returned.
Method Syntax
db.auth<T>()
Returns
AuthPromise<T> - A promise for the authenticated user record
Example
const user = await db.auth();
console.log('Current user:', user);
See Also