@surrealdb/ql-wasm
v4.0.0
Published
WebAssembly utility functions for SurrealQL
Downloads
14,373
Readme
@surrealdb/ql-wasm
WebAssembly utility functions for SurrealQL: validate and format queries, and convert SurrealQL values between their text, JSON and CBOR forms. The package is built from the SurrealDB engine, so it parses the SurrealQL of the engine release it shares a version with.
Importing the module
import { SurrealQL, Value, CborFormat } from '@surrealdb/ql-wasm';Or from a CDN:
import { SurrealQL, Value, CborFormat } from 'https://unpkg.com/@surrealdb/ql-wasm/dist/surrealql/index.js';The module loads its .wasm file from beside dist/surrealql/index.js, over
file:, http(s): and tauri: URLs. A bundler has to copy
dist/surrealql/*.wasm to wherever it serves the loader from.
Queries
// Validating: returns nothing, or throws the parse error as a string
SurrealQL.validate("SELECT * FROM person");
// Formatting, optionally over several lines
SurrealQL.format("SELECT * FROM person", true);
// Listing the tables a record type refers to
SurrealQL.extract_tables_from_kind("record<a | b | c>");
// ["a", "b", "c"]Values
// Creating a SurrealQL value
const value = Value.from_string('{ id: person:tobie }');
const value = Value.from_json({ id: "person:tobie" });
const value = Value.from_json_string('{ "id": "person:tobie" }');
const value = Value.from_cbor(/* Uint8Array */);
// Formatting a value
value.format(false);
value.format(true); // Pretty
value.json(true); // Pretty JSON
// Converting a value to CBOR, represented as a Uint8Array
value.to_cbor();
// Release the value's memory when it is no longer needed
value.free();CBOR dialects
from_cbor and to_cbor take an optional CborFormat. Without one they use
the plain cbor protocol, which every server speaks. CborFormat.Cbor2 is the
cbor.2 protocol of SurrealDB 4.0, which keeps a value's exact type across the
round trip: sized integers and floats, big decimals, dates, times, timestamps,
intervals and regexes. Plain cbor cannot carry a regex, and writes an interval
as text and a date as a datetime.
Both ends of a conversion must use the same dialect:
import { CborCodec } from 'surrealdb';
const codec = new CborCodec({ version: 2 });
const bytes = Value.from_string('/^a+$/').to_cbor(CborFormat.Cbor2);Errors
Every function throws a plain string, never an Error object.
