SurrealQueryableThe 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
apiAccess 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 Accessconst api = db.api(); const result = await api.get('/users');
Type-Safe API Accesstype 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 Prefixconst usersApi = db.api<MyPaths>("/users"); const user = await usersApi.get("123"); // GET /users/123
.query()Execute raw SurrealQL statements against the database.
Method Syntaxdb.query<R>(query, bindings?) db.query<R>(boundQuery)
| 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). |
R extends unknown[] - Array of result types for each query statementQuery<R> - A query instance that can be configured and executed
Simple Queryconst result = await db.query('SELECT * FROM users').collect(); console.log(result); // [{ success: true, result: [...] }]
Query with Bindingsconst result = await db.query( 'SELECT * FROM users WHERE age > $age', { age: 18 } ).collect();
Multiple Statementsconst results = await db.query<[User[], Post[]]>(` SELECT * FROM users; SELECT * FROM posts; `).collect(); const [users, posts] = results.map(r => r.result);
Using BoundQueryimport { 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 Syntaxdb.select<T>(recordId) db.select<T>(range) db.select<T>(table)
| 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. |
SelectPromise<T> - A promise with chainable configuration methods
Select by Record IDconst user = await db.select(new RecordId('users', 'john'));
Select All from Tableconst users = await db.select(new Table('users'));
Select with Configurationconst users = await db.select(new Table('users')) .where('age > 18') .limit(10) .start(0);
.create()Create new records in the database.
Method Syntaxdb.create<T>(recordId) db.create<T>(table)
| 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). |
CreatePromise<T> - A promise with chainable configuration methods
Create with Specific IDconst user = await db.create(new RecordId('users', 'john')) .content({ name: 'John Doe', email: 'john@example.com' });
Create with Auto-Generated IDconst 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 Syntaxdb.insert<T>(data) db.insert<T>(table, data)
| Parameter | Type | Description |
|---|---|---|
table optional | Table | The table to insert records into. |
data required | T | T[] | One or more records to insert. |
InsertPromise<T> - A promise with chainable configuration methods
Insert Single Recordconst user = await db.insert({ id: new RecordId('users', 'alice'), name: 'Alice', email: 'alice@example.com' });
Insert Multiple Recordsconst users = await db.insert([ { id: new RecordId('users', 'bob'), name: 'Bob' }, { id: new RecordId('users', 'carol'), name: 'Carol' } ]);
Insert into Tableconst users = await db.insert(new Table('users'), [ { name: 'Dave' }, { name: 'Eve' } ]);
.update()Update existing records in the database.
Method Syntaxdb.update<T>(recordId) db.update<T>(range) db.update<T>(table)
| 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. |
UpdatePromise<T> - A promise with chainable configuration methods
Update with Contentconst user = await db.update(new RecordId('users', 'john')) .content({ name: 'John Smith', email: 'john@example.com' });
Update with Mergeconst user = await db.update(new RecordId('users', 'john')) .merge({ email: 'newemail@example.com' });
Update with Conditionconst 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).
WarningThis function replaces existing record data with the specified data.
Method Syntaxdb.upsert<T>(recordId) db.upsert<T>(range) db.upsert<T>(table)
| 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. |
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()Delete records from the database.
Method Syntaxdb.delete<T>(recordId) db.delete<T>(range) db.delete<T>(table)
| 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. |
DeletePromise<T> - A promise with chainable configuration methods
Delete Single Recordconst deleted = await db.delete(new RecordId('users', 'john'));
Delete All from Tableconst deleted = await db.delete(new Table('users'));
.relate()Create graph relationships (edges) between records.
Method Syntaxdb.relate<T>(from, edge, to, data?) db.relate<T>(from[], edge, to[], data?)
| 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. |
RelatePromise<T> - A promise for the relationship operation
Create Single Relationshipconst edge = await db.relate( new RecordId('users', 'john'), new Table('likes'), new RecordId('posts', '1'), { timestamp: new Date() } );
Create Multiple Relationshipsconst 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 Syntaxdb.live<T>(what)
| Parameter | Type | Description |
|---|---|---|
what required | LiveResource | The 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); }
.liveOf()Subscribe to an existing live query using its ID.
NoteThis function is for use with live queries not managed by the driver.
Method Syntaxdb.liveOf(id)
| Parameter | Type | Description |
|---|---|---|
id required | Uuid | The 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);
.run()Execute a SurrealDB function or SurrealML model.
Method Syntaxdb.run<T>(name, args?) db.run<T>(name, version, args?)
| 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. |
RunPromise<T> - A promise for the function result
Run Custom Functionconst result = await db.run('fn::calculate', [10, 20]);
Run SurrealML Modelconst prediction = await db.run('ml::predict', '1.0.0', [inputData]);
.auth()Get the currently authenticated record user by selecting the $auth parameter.
NoteThe user must have permission to select their own record, otherwise an empty result is returned.
Method Syntaxdb.auth<T>()
AuthPromise<T> - A promise for the authenticated user record
const user = await db.auth(); console.log('Current user:', user);