Skip to content

Querying

.query() instance method

Executes a custom SurrealQL query.

query(
surql: string | object,
vars?: { [p: string]: unknown },
options?: ClientRpcOptions,
): Promise<unknown[]>;

Arguments

surql

A SurrealQL string or a pre-prepared query.

vars

Variables to pass during SurrealQL execution. Note that variable names should not start with a dollar sign ($).

options

Options for the RPC request.

Return Value

Returns a Promise object that resolves to an array of the SurrealQL execution results. If one or more statements fail, it rejects with a QueryFailedError containing the error messages.

There is no way to obtain the execution results if this method rejects. If you need to handle errors manually, you can use .queryRaw().

Examples

The following example successfully executes a query:

import { Surreal } from "@tai-kun/surrealdb";
const db = new Surreal();
await db.connect("ws://localhost:8000");
const results = await db.query(`
CREATE ONLY user:foo CONTENT { age: 42 };
`);
console.log(results);
// [{
// id: Thing { tb: 'user', id: 'foo' },
// age: 42
// }]
await db.close();

The following example will reject the query with a QueryFailedError because one of the statements fails:

import { Surreal } from "@tai-kun/surrealdb";
const db = new Surreal();
await db.connect("ws://localhost:8000");
const results = await db.query(`
CREATE ONLY user:foo CONTENT { age: 42 };
OUTPUT 42;
`); // throws QueryFailedError: Query failed with 1 error(s)

The following example executes a pre-prepared query:

import { surql, Surreal, Thing } from "@tai-kun/surrealdb";
const CreateUserQuery = surql`
CREATE ONLY user:foo CONTENT { age: 42 };
`.returns<[{ id: Thing<"user">, age: number }]>()
const db = new Surreal();
await db.connect("ws://localhost:8000");
const results = await db.query(CreateUserQuery);
// ^? const results: [{ id: Thing<"user">, age: number }]
await db.close();

.queryRaw() instance method

Executes a custom SurrealQL query.

queryRaw(
surql: string | object,
vars?: { [p: string]: unknown },
options?: ClientRpcOptions,
): Promise<QueryResult[]>;

Arguments

surql

A SurrealQL string or a pre-prepared query.

vars

Variables to pass during SurrealQL execution. Note that variable names should not start with a dollar sign ($).

options

Options for the RPC request.

Return Value

Returns a Promise object that resolves to an array of the SurrealQL execution results.

type QueryResult = {
status: "OK";
time: string;
result: unknown;
} | {
status: "ERR";
time: string;
result: string;
};