A thin TypeScript wrapper around the full HTTP API. Intended for use on servers and other trusted contexts. For browsers and other untrusted clients, see React, Zero, or TanStack DB.
Setup
createClient
import { createClient } from "@rindle/api";
const db = createClient({
url: process.env.RINDLE_URL,
apiToken: process.env.RINDLE_API_TOKEN,
});| Option | |
|---|---|
url |
Rindle’s address. Defaults to RINDLE_URL. |
apiToken |
Defaults to RINDLE_API_TOKEN. Leave it out locally. |
stream |
Where query opens its stream, when wsPort gives it its own port. Defaults to url. |
fetch |
A custom fetch. |
The client has full access to the database. Nothing is fetched until the first call.
close
db.close() stops the client’s live queries.
SQL
execute
const { rowsAffected } = await db.execute({
sql: "INSERT INTO issue (id, title, closed) VALUES (?, ?, ?)",
params: [crypto.randomUUID(), "first", 0],
});Runs one statement (/db/execute). A statement is a string, or { sql, params },
where params is an array for ? or an object for :name. Schema changes throw; use migrate.
A failed write is not retried.
Writes are a subset of SQLite DML: an INSERT names its key, and an
UPDATE/DELETE takes a WHERE over the table’s own columns. An expression in a SET, a
pattern match or a subquery throws with the rewrite in the message.
Returns:
columns |
{ name, decltype }[] |
rows |
Arrays in column order. A SELECT here is a rectangle; use read for the tree. |
rowsAffected |
The rows the statement addressed: the rows a WHERE matched, or 1 per keyed statement whether or not its row was there. |
lastInsertRowid |
Always null — the store has no rowid, and a keyed write names its own key. |
batch
db.batch(statements) runs statements in one transaction (/db/batch). Returns
one result per statement.
transaction
await db.transaction(async (tx) => {
const { rows } = await tx.execute({
sql: "SELECT stock FROM item WHERE id = ?",
params: [id],
});
const stock = Number(rows[0][0]);
if (stock === 0) throw new Error("sold out");
await tx.execute({
sql: "UPDATE item SET stock = ? WHERE id = ?",
params: [stock - 1, id],
});
});An interactive transaction (/db/transactions). Commits when fn
resolves and rolls back when it throws. tx has execute and batch.
The read-then-write above is exactly what this is for: a SET takes literal values, so
SET stock = stock - 1 is refused — read the row, compute, write it back. The transaction is
what makes that safe.
Each transaction uses a private snapshot. Other transactions can run and commit while it remains open. The server validates and replays its writes through one committer at commit.
A conflict throws an error whose code is TRANSACTION_CONFLICT, and nothing is applied.
transaction does not rerun your callback: catch the conflict and call it again, so the callback
must be safe to repeat.
The default idle limit is five seconds after the last operation finishes. The absolute limit is 30 seconds from begin.
A db.read issued while you hold a transaction is safe and does not wait for it, but it reads the
latest committed state: it does not see your transaction’s uncommitted writes. Read through
tx for read-your-writes, and with db.read when you want the committed state.
migrate
await db.migrate("0001_init", `
CREATE TABLE issue (
id TEXT PRIMARY KEY,
title TEXT,
closed INTEGER
);
`);Applies a schema change once, by name (/db/migrate). Calling it again with the
same name does nothing and returns { applied: false }. A different script under a name that’s
already applied throws.
Takes CREATE/DROP TABLE, ADD/DROP/RENAME COLUMN, RENAME TO and
CREATE/DROP INDEX. Every table needs a primary key, and your app supplies its values:
AUTOINCREMENT is not supported yet. SQL has the full list and what is refused.
Queries
query
const issues = await db.query<Issue>(
"SELECT * FROM issue WHERE closed = ? ORDER BY id DESC LIMIT 50",
[0],
);
issues.subscribe((rows) => console.log(rows));Starts a live query, over /db/subscribe and
/db/stream. The query is Rindle SQL or a builder query;
params are strings, numbers, booleans and null. Rejects with SqlCompileError if the query
can’t be kept live. An optional third argument, { mode: "pulse" }, starts a pulse.
Returns a LiveQuery<Row>:
data |
The current rows. |
resultType |
"unknown" until the first rows arrive, then "complete". Tells “no rows yet” from “no rows”. |
engineMs |
How long the engine took to produce the first result (engineMs). undefined until it arrives. |
hydrateMs |
How long the engine took to build and hydrate the query when it first started, which may be before this subscription joined it (hydrateMs). undefined until the first result arrives. |
subscribe(listener) |
Calls listener(rows) now and after every change. Returns an unsubscribe function. |
destroy() |
Stops the query. |
The same query and params, started twice, share one query on the server.
Pulses
const pulse = await db.query(
"SELECT * FROM issue WHERE closed = ? ORDER BY id DESC LIMIT 50",
[0],
{ mode: "pulse" },
);
pulse.subscribe(() => console.log("changed"));With { mode: "pulse" }, the query sends no rows, only that its result changed (a
"pulse" subscription). Rindle still keeps it live, and shares it with
everyone else who subscribes the same query. A db client can hold 20,000 pulses.
Returns a LivePulse:
resultType |
"unknown" until the query is live, then "complete". |
subscribe(listener) |
Calls listener() after each commit that changed the result. Returns an unsubscribe function. |
destroy() |
Stops the query. |
read
db.read(sql, params?) runs a query once and returns its rows (/db/query). It
takes the same queries as query.
Streams
These serve your app’s clients. See Architecture.
authorizeStream
const { streamToken } = await db.authorizeStream({
clientID,
userID: user.id,
streamToken,
});Gets a stream token for one client (/db/stream-auth). userID is
optional. streamToken is the client’s previous stream token, once it has one. To save the client a
round trip on page load, call it while server-rendering the page and put the stream token in the
HTML.
subscribe
const result = await db.subscribe({
clientID,
subscriptionID,
userID: user.id,
streamToken,
sql: "SELECT id, title FROM note WHERE owner_id = ? ORDER BY id",
params: [user.id],
});Adds one subscription to a client (/db/subscribe). In place of sql and
params, pass a builder query as query. mode: "pulse" sends only that the result changed.
userID is optional. streamToken is the client’s latest stream token.
Returns { id, status: "ok" }, or status: "error" with code, httpStatus and message.
unsubscribe
db.unsubscribe({ clientID, subscriptionID, userID, streamToken }) removes one. Returns the same
result.
subscribeOps
const results = await db.subscribeOps({
clientID,
userID: user.id,
streamToken,
ops: [
{ op: "remove", id: 17 },
{
op: "add",
id: 18,
sql: "SELECT * FROM note WHERE folder = ?",
params: [3],
},
],
});Adds and removes several in one request, in order. Returns one result per op.
deauthorizeStream
db.deauthorizeStream({ userID, clientID? }) ends a user’s streams, or one client’s
(/db/stream-deauth). Returns { ended }.