---
name: building-rindle-apps
description: >-
  Build apps on Rindle, a reactive SQL database: write ordinary SQL, and
  queries stay live, pushing new results to a web page or a Node process after
  every write. Use when the user names Rindle, rindled, or @rindle packages, or
  asks for a realtime, live-updating, collaborative, or multiplayer app built on
  Rindle. Covers Cloud Rindle setup, web apps on TanStack
  Start, Next.js or Cloudflare Workers with React, instant UI (preloading and
  optimistic writes), per-user permissions, and Node workers. For work on the Rindle engine itself, use the repository's agent
  instructions.
---

# Building apps with Rindle

If you fetched this file from https://www.rindle.sh/skill.md, first save it into
this project's skills folder as `building-rindle-apps/SKILL.md` (`.claude/skills/` for Claude Code,
`.agents/skills/` for most other agents), so later sessions have it too.

Rindle is a SQL database where any `SELECT` can be made **live**: the database pushes the new
result every time a write changes it, from any process. There is no schema language, ORM, or sync
framework to learn. You write SQL tables, SQL writes, and SQL queries.

Rindle fits into an app like any other database. **The browser never sends Rindle SQL.** It names
a query and calls the app's own API server, which checks the user, picks the SQL for that name,
and asks Rindle to keep that query live. The rows arrive on a stream the page reads straight from
Rindle, and that stream carries only what the app added. Writes are ordinary endpoints too. That is how
authorization works: there is no separate permission system.

**Before writing a web app, read https://www.rindle.sh/architecture.md and
https://www.rindle.sh/react-api.md** (a Node-only project can skip them). Architecture is the
model: the stream, stream tokens, subscriptions, write endpoints and permissions, shown with one
route per query (`db.subscribe`). The React page is what to build: the page names queries with
`useQuery`, and **two** routes on your server (`auth` and `subscribe`, which uses
`db.subscribeOps`) serve every query, plus server rendering. This file covers what they don't:
installing, connecting to Cloud Rindle, project setup, the live SQL subset, the keyed write subset,
schema, and Node workers.

Every docs page is also served as plain Markdown: add `.md` to its path
(`https://www.rindle.sh/sql.md`). Fetch that form; it has every code sample, which a summarized
HTML page may not.

## The default path

Use this unless the user explicitly asks for something else:

- **Database:** Cloud Rindle, the hosted database (see "Connect to Cloud Rindle"). There is no
  database to install or run on this machine.
- **API server and page:** TanStack Start (React, deploys to Vercel, Netlify, Cloudflare or any
  Node host). Use Next.js when the user asks for it or the project already is one, and a
  Cloudflare Worker serving a Vite + React page when they ask for a Worker.
- **Instant UI:** preload what the user is likely to open next and show their own writes before
  the server answers (see "Instant UI"). Do this by default in anything interactive.
- **Client:** `@rindle/api` on the server, and `useQuery` from `@rindle/react` in the page.
- **Background work** (agents, bots, workers, importers): plain Node scripts with `@rindle/api`.
  They run on your side of the boundary, so they talk to Rindle directly.

Everything else about Rindle (the full SQL reference, the TypeScript and React APIs, SSR, the HTTP
API, deploying to Cloud Rindle) is in the live docs at
https://www.rindle.sh (the index is https://www.rindle.sh/llms.txt). Read the relevant page
there before using anything this file and those two pages don't cover.

## Install Rindle

In the project root (after scaffolding the app, below):

```sh
npm install @rindle/api @rindle/react
npm install --save-dev @rindle/cli
```

`@rindle/api` is the server client. `@rindle/react` is the page's hook, and under
`@rindle/react/server` the server render's client; both depend on `@rindle/client`. `@rindle/cli`
is the Cloud CLI, run as `npx rindle` in the project root (without it installed, npx would fetch an
unrelated package that happens to be named `rindle`). A Node-only project needs only `@rindle/api`
and `@rindle/cli`. Without a `package.json`, run `npm init -y && npm pkg set type=module` first.
Node 22.18 or later is needed.

## Connect to Cloud Rindle

The database is hosted on Cloud Rindle (https://www.rindle.sh/cloud.md). Nothing runs on this
machine: the app reaches the database at `RINDLE_URL` with `RINDLE_API_TOKEN`, in development and
in production. Anything holding the token can write, which is why only your server may know it.

If the user already has a database (a `.env` with `RINDLE_URL` and `RINDLE_API_TOKEN`, or both
values from the dashboard at https://cloud.rindle.sh), use it and go to step 3. Otherwise, install
`@rindle/cli` first (see "Install Rindle"), because `npx rindle` without it fetches an unrelated
package:

1. The user runs `npx rindle login` themselves: it opens a browser to confirm a code, so don't
   run it for them. Wait until they say it's done (`npx rindle whoami` shows the account).
2. Run `npx rindle deploy` in the project root. It creates the database and prints
   `RINDLE_URL=https://…` and `RINDLE_API_TOKEN=…`. If it says the database is **in the
   queue**, every server is full: the database exists and starts on its own when one has room,
   and the user is emailed when it does. Tell the user (the output says where it stands in
   line), carry on with the app code, and run `npx rindle deploy` again later. Nothing can be
   migrated or queried until it reports the database ready.
3. Put both lines in `.env` (and `.dev.vars` for a Worker) for local development, and in the
   hosting provider's server environment for production. Add `.env` (and, for a Worker,
   `.dev.vars` and `.wrangler`) to `.gitignore`: never commit them or send them to the browser.
   `.rindle/cloud.json` is safe to commit.
4. Run the migration script (see "Schema and migrations") against that environment.

## Project setup

Keep server code (sessions, routes, the SQL) in server-only modules. Nothing the browser loads
may import `@rindle/api`, know `RINDLE_API_TOKEN`, or contain the app's SQL. Create the
server client once, in one module every route imports (in a Worker, put it beside
`worker/index.ts`):

```ts
// src/server/rindle.ts — server only
import { createClient } from "@rindle/api";

// Reads RINDLE_URL and RINDLE_API_TOKEN. Construction does no I/O.
export const db = createClient();
```

The page's live queries go through **two** routes under one base path, both on the React
page and both thin wrappers over this client:

- `POST /api/rindle/auth` takes `{ clientID, streamToken }` and returns `db.authorizeStream(...)`.
  The page calls it before its first subscribe and every few minutes to keep the stream open.
- `POST /api/rindle/subscribe` takes `{ clientID, streamToken, ops }` and maps each query name the
  page asks for to SQL with the app's own `queryFor(user, name, args)` (a server-only module,
  usually `src/server/queries.ts`), then passes the batch to `db.subscribeOps(...)` and returns one
  result per op, in order.

Pass Rindle's refusals through with their status rather than as a `500`. When the page's stream
token is from a database that restarted, `authorizeStream` throws a `RindleRequestError` with code
`client-lost` and `httpStatus` 409, and the page starts its client over only if your route answers
409:

Write each route as a plain `(request: Request) => Promise<Response>` handler in a server-only
module, and mount it the way the framework does (see "TanStack Start" below):

```ts
// src/server/rindle-routes.ts
import { RindleRequestError } from "@rindle/api";
import { db } from "./rindle";
import { getUser } from "./auth";

export async function auth(request: Request): Promise<Response> {
  const user = await getUser(request);
  if (!user) return new Response(null, { status: 401 });
  const { clientID, streamToken } = await request.json();
  try {
    return Response.json(await db.authorizeStream({ clientID, userID: user.id, streamToken }));
  } catch (e) {
    if (e instanceof RindleRequestError) {
      return Response.json({ code: e.code, message: e.message }, { status: e.httpStatus });
    }
    throw e;
  }
}
```

Wrap `db.subscribeOps` in the subscribe route the same way.

Refuse a query per op, not per batch: one page tick can carry several queries, and a throw that
fails the whole request fails them all. `queryFor` may be async, to check membership with
`db.read`:

```ts
// src/server/rindle-routes.ts, continued
import type { OpResult, QueryParam, SubscribeOp } from "@rindle/api";
// (user, name, args) => Promise<{ sql: string; params?: QueryParam[] }>; throws to refuse
import { queryFor } from "./queries";

export async function subscribe(request: Request): Promise<Response> {
  const user = await getUser(request);
  if (!user) return new Response(null, { status: 401 });
  type PageOp = { op: "add"; id: number; name: string; args?: unknown } | { op: "remove"; id: number };
  const { clientID, streamToken, ops } = (await request.json()) as {
    clientID: string; streamToken: string; ops: PageOp[];
  };
  const refused = new Map<number, OpResult>();
  const send: SubscribeOp[] = [];
  for (const op of ops) {
    if (op.op === "remove") { send.push(op); continue; }
    try {
      send.push({ op: "add", id: op.id, ...(await queryFor(user, op.name, op.args)) });
    } catch (e) {
      refused.set(op.id, { id: op.id, status: "error", code: "forbidden", httpStatus: 403, message: (e as Error).message });
    }
  }
  const sent = send.length
    ? await db.subscribeOps({ clientID, userID: user.id, streamToken, ops: send })
    : [];
  const byID = new Map(sent.map((r) => [r.id, r]));
  return Response.json(ops.map((op) => refused.get(op.id) ?? byID.get(op.id)));
}
```

The page sees a refused query as that query's `error`, with `status` 403.

There is no stream route: the `auth` route's reply carries a short-lived `streamToken`, and the
browser client opens the stream **straight from Rindle** with it. So the page is built with
Rindle's public address, the browser client's required `stream` option: `RINDLE_URL`'s origin,
without the token. Each framework below puts it in the page's build as
`process.env.RINDLE_STREAM_URL`.

### TanStack Start

```sh
npx -y @tanstack/cli@latest create my-app --blank --package-manager npm --no-git --no-intent --no-toolchain --non-interactive
cd my-app
# then install Rindle (see "Install Rindle")
```

`--blank` is one route with no Tailwind or demo pages; add `--deployment vercel` (or `netlify`,
`cloudflare`) when the user names a host. The template already has `"type": "module"`, imports
`#/…` from `src/`, and `defaultPreload: "intent"` in `src/router.tsx`. Its `dev` script pins
port 3000: change it in `package.json`, or run `npm run dev -- --port <n>`. Put the server modules
in `src/server/`. Server code reads `RINDLE_URL` and `RINDLE_API_TOKEN` from `.env` in `npm run dev`
and `npm run preview`, so that file is all local development needs.

Put the stream address into the page's build in `vite.config.ts` (a browser bundle has no
`process.env`), keeping the template's plugins:

```ts
// vite.config.ts
import { defineConfig, loadEnv } from "vite";
import { tanstackStart } from "@tanstack/react-start/plugin/vite";
import viteReact from "@vitejs/plugin-react";

export default defineConfig(({ mode }) => {
  // From .env, or from the build's own environment.
  const env = loadEnv(mode, process.cwd(), "");
  const rindle = env.RINDLE_URL;
  return {
    resolve: { tsconfigPaths: true },
    plugins: [tanstackStart(), viteReact()],
    define: { "process.env.RINDLE_STREAM_URL": JSON.stringify(rindle ? new URL(rindle).origin : "") },
  };
});
```

and declare it for TypeScript in `src/env.d.ts`. Its first line loads TanStack Start's types,
which the blank template never imports; without it `tsc` fails on every API route with
"'server' does not exist in type …":

```ts
// src/env.d.ts
/// <reference types="@tanstack/react-start" />
declare namespace NodeJS {
  interface ProcessEnv {
    RINDLE_STREAM_URL: string;
  }
}
```

Every route is a file under `src/routes/`, API routes included. Mount each handler as a server
route:

```ts
// src/routes/api/rindle/subscribe.ts
import { createFileRoute } from "@tanstack/react-router";
import { subscribe } from "#/server/rindle-routes";

export const Route = createFileRoute("/api/rindle/subscribe")({
  server: { handlers: { POST: ({ request }) => subscribe(request) } },
});
```

`/api/rindle/auth`, the write endpoints and sign-in are the same, one file each
(`src/routes/api/polls/$id.vote.ts` for `/api/polls/$id/vote`, with `params.id` in the handler).
A path that also has paths under it goes in an `index.ts` (`src/routes/api/polls/index.ts` for
`POST /api/polls`). Pages are routes with a `component`, and `$id` in a file name is a path param
(`src/routes/poll.$id.tsx`, read with `Route.useParams()`). The dev server writes
`src/routeTree.gen.ts` whenever a route file changes, so run `tsc` after `npm run dev` has
started once. Wrap the signed-in part of the page in `<SignedIn>` (see "The page's client")
inside the root route's `RootDocument`.

The root route's component stays mounted across navigation, and a page route's does not. So the
`useQuery` that preloads (see "Instant UI") goes in the root route, or in a layout route above
the pages it feeds, and the pages read its rows from context.

TanStack Start renders every route on the server too. Without an SSR client, `useQuery` renders
`status: "loading"` there and goes live in the browser, so the first paint is the loading state.
That is the default here.

**Server rendering on TanStack Start.** When the user wants the first load to show the rows, read
https://www.rindle.sh/react-api#server-rendering, then replace the two entries TanStack Start
otherwise generates. The server entry renders each request inside an SSR client and adds its
script once the stream has finished:

```tsx
// src/server.tsx
import {
  createServerEntry, createStartHandler, defineHandlerCallback, StartServer,
} from "@tanstack/react-start/server";
import { renderRouterToStream } from "@tanstack/react-router/ssr/server";
import { RindleProvider } from "@rindle/react";
import { createSSRClient } from "@rindle/react/server";
import { db as rindle } from "#/server/rindle";
import { getUser } from "#/server/auth";
import { queryFor } from "#/server/queries";

const render = defineHandlerCallback(async ({ request, router, responseHeaders }) => {
  const user = await getUser(request);
  const db = createSSRClient({ rindle, queries: (name, args) => queryFor(user, name, args), userID: user?.id });
  responseHeaders.set("Cache-Control", "private, no-store");
  const rendered = await renderRouterToStream({
    request, router, responseHeaders,
    children: <RindleProvider client={db}><StartServer router={router} /></RindleProvider>,
  });
  // The page's script goes last, after every query the render read.
  const script = new TextEncoder();
  const body = rendered.response.body!.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
    flush: (out) => out.enqueue(script.encode(`<script>${db.dehydrateScript()}</script>`)),
  }));
  return { ...rendered, response: new Response(body, rendered.response) };
});

export default createServerEntry({ fetch: createStartHandler(render) });
```

The browser entry creates the page's one client with `hydrate: true` and wraps the app in it:

```tsx
// src/client.tsx
import { StrictMode, startTransition } from "react";
import { hydrateRoot } from "react-dom/client";
import { StartClient } from "@tanstack/react-start/client";
import { createClient, RindleProvider } from "@rindle/react";

const db = createClient({ base: "/api/rindle", stream: process.env.RINDLE_STREAM_URL!, hydrate: true });

startTransition(() => {
  hydrateRoot(document, (
    <StrictMode>
      <RindleProvider client={db}><StartClient /></RindleProvider>
    </StrictMode>
  ));
});
```

Then don't use `<SignedIn>`: the client lives as long as the page, so sign-in and sign-out finish
with a full page load (`location.assign("/")`), which gives the next user a fresh client and a
fresh server render. A first-visit cookie (an anonymous visitor id) is set in the server entry:
mint it when `getUser` finds none, add `Set-Cookie` to `responseHeaders`, and render with it. In a
test, the server-rendered rows are on screen before the page hydrates, so wait for hydration (for
example, until the WebSocket whose URL contains `/db/stream` opens; in `npm run dev`, Vite opens
a socket of its own first) before clicking.

`npm run build` then `npm run preview` serves the production build locally. Deploying needs the
host's adapter: `--deployment` at create time, or TanStack Start's hosting guide.

### Next.js

```sh
npx create-next-app@latest my-app --ts --app --eslint --no-tailwind --no-src-dir --use-npm --yes
cd my-app
# then install Rindle (see "Install Rindle")
```

Add `"type": "module"` to the `package.json` create-next-app wrote, so Node runs the migration
script as ESM. Next.js reads `.env`, so the Cloud lines there are all the configuration local
development needs. Put the server modules in `lib/` instead of
`src/server/` (create-next-app's `@/` alias points at the project root). Routes are route files,
each mounting its handler: `export { subscribe as POST } from "@/lib/rindle-routes";` in
`app/api/rindle/subscribe/route.ts`. The page that calls `useQuery` is a client component
(`"use client"`). Add `env` to the config in `next.config.ts`, keeping what create-next-app put
there, so the stream address is in the page's build:

```ts
// next.config.ts
import type { NextConfig } from "next";

// From .env, or from the build's own environment.
const rindle = process.env.RINDLE_URL;

const config: NextConfig = {
  // …create-next-app's settings…
  env: { RINDLE_STREAM_URL: rindle ? new URL(rindle).origin : "" },
};
export default config;
```


create-next-app turns on `cacheComponents` (keep its `next.config.ts` settings), so a page that
reads `params` (a share link like `/poll/[id]`) is a server `page.tsx` whose `await params` sits
in an async child inside `<Suspense>`; awaiting it in the page body fails the route with "runtime
data … accessed outside of `<Suspense>`":

```tsx
// app/poll/[id]/page.tsx
import { Suspense } from "react";
import { PollView } from "./PollView"; // "use client"

export default function Page({ params }: { params: Promise<{ id: string }> }) {
  return <Suspense fallback={null}><Poll params={params} /></Suspense>;
}

async function Poll({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  return <PollView id={id} />;
}
```

**Server rendering.** If the user wants pages rendered on the server with their live rows (the
first load shows data, then stays live), read
https://www.rindle.sh/react-api#server-rendering before writing it, including
its Next.js section. Don't fetch the rows separately with `db.read` and pass them down: the SSR
client (`createSSRClient` from `@rindle/react/server`) hands the server's queries to the page
without a second request.

With `cacheComponents` on, the docs' root layout fails `next build` ("Next.js encountered
uncached or runtime data during prerendering … accessed outside of `<Suspense>`"), because
`beginRender` and your session lookup read the request. Move that part into an async component
inside `<Suspense>`:

```tsx
// app/layout.tsx
import { Suspense, type ReactNode } from "react";
import { beginRender } from "@/lib/render";
import { currentUser } from "@/lib/auth";
import { RindleRoot } from "./RindleRoot";

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <Suspense fallback={null}>
          <WithRindle>{children}</WithRindle>
        </Suspense>
      </body>
    </html>
  );
}

async function WithRindle({ children }: { children: ReactNode }) {
  const ssrID = await beginRender(await currentUser());
  return <RindleRoot ssrID={ssrID}>{children}</RindleRoot>;
}
```

In `RindleRoot`, pass `stream: process.env.RINDLE_STREAM_URL!` where the docs write
`"https://rindle.example.com"`.

### Cloudflare Worker

A Vite + React page served as static assets, with the Worker answering `/api/*`:

```sh
npm create vite@latest my-app -- --template react-ts --no-interactive
cd my-app
npm i -D @cloudflare/vite-plugin wrangler
# then install Rindle (see "Install Rindle")
```

```ts
// vite.config.ts
import { cloudflare } from "@cloudflare/vite-plugin";
import react from "@vitejs/plugin-react";
import { defineConfig, loadEnv } from "vite";

export default defineConfig(({ mode }) => {
  // The page's `stream` address, read from .env at build time (a browser bundle has no process.env).
  const env = loadEnv(mode, process.cwd(), "");
  const rindle = env.RINDLE_URL;
  return {
    plugins: [react(), cloudflare()],
    build: { target: "es2022" },
    define: { "process.env.RINDLE_STREAM_URL": JSON.stringify(rindle ? new URL(rindle).origin : "") },
  };
});
```

```jsonc
// wrangler.jsonc
{
  "name": "my-app",
  "main": "./worker/index.ts",
  "compatibility_date": "2026-05-28",
  "compatibility_flags": ["nodejs_compat"], // puts vars and secrets on process.env
  "assets": { "not_found_handling": "single-page-application", "run_worker_first": ["/api/*"] }
}
```

`worker/index.ts` routes each `/api/...` path to its handler, reading secrets from `process.env`
as the snippets here do:

```ts
// worker/index.ts
export default {
  async fetch(request: Request): Promise<Response> {
    const { pathname } = new URL(request.url);
    const m = request.method;
    if (pathname === "/api/rindle/auth" && m === "POST") return auth(request);
    if (pathname === "/api/rindle/subscribe" && m === "POST") return subscribe(request);
    if (pathname === "/api/todos" && m === "POST") return createTodo(request);
    const done = pathname.match(/^\/api\/todos\/([\w-]+)\/done$/);
    if (done && m === "POST") return markDone(request, done[1]);
    // …login, me, logout
    return new Response("Not found", { status: 404 });
  },
};
```

`npm run dev` (Vite, on port 5173) runs the Worker in workerd. The Vite template's `tsc -b` checks
only `src/`: add a `tsconfig.worker.json` (`"include": ["worker"]`, `"types":
["@cloudflare/workers-types", "node"]`, after `npm i -D @cloudflare/workers-types @types/node`)
to the root `tsconfig.json`'s `references`. In `src/`, declare the one variable Vite's `define`
fills, in `src/env.d.ts`: `declare const process: { env: { RINDLE_STREAM_URL: string } };`. Wrangler's local dev reads variables from
`.dev.vars`, so copy the `RINDLE_URL` and `RINDLE_API_TOKEN` lines from `.env` there (and add `SESSION_SECRET`, below), or
start Vite with `CLOUDFLARE_INCLUDE_PROCESS_ENV=true` and the variables in the environment.
Clients can be created at module scope — `createClient` does no I/O — but never `await` I/O there:
a Worker can only do I/O inside a request.

**Server rendering on a Worker.** The Worker renders the page itself, as in the React page's
server entry, into Vite's own `index.html` rather than a hand-written shell:

- In `wrangler.jsonc`, add `"binding": "ASSETS"` to `assets`, and list the rendered page paths in
  `run_worker_first` (`["/api/*", "/", "/p/*"]`), or the static SPA shell answers them.
- The handler takes `fetch(request, env, ctx)`. Fetch the shell with
  `env.ASSETS.fetch(new URL("/index.html", request.url))` (in `npm run dev` the Cloudflare plugin
  serves the transformed dev HTML), put the rendered app inside `<div id="root">` and
  `<script>${db.dehydrateScript()}</script>` before `</body>`, and keep the SSR client's queries
  until the browser takes over with `ctx.waitUntil(Promise.race([db.handedOff, timeout]))`.
- A first-visit cookie (an anonymous visitor id) goes on that rendered response's `Set-Cookie`.
- `npm i -D @cloudflare/workers-types` for `ExecutionContext` and `Fetcher`, and add `"node"`
  to the Worker tsconfig's `types` for `process.env`.

### Sign-in

Use the app's existing auth if it has one: routes only need the user's id. For a new app with no
auth, a stand-in session is enough: a name, kept in an **HttpOnly** cookie signed with
`SESSION_SECRET`, so page scripts (and an XSS) can't read it. Never keep the session or a token in
`localStorage` or anywhere page scripts can read.

```ts
// src/server/auth.ts — WebCrypto, so it runs on Node and Workers
const COOKIE = "session";
const secret = () => process.env.SESSION_SECRET || "dev-only-secret";
const enc = new TextEncoder();

async function sign(value: string) {
  const key = await crypto.subtle.importKey("raw", enc.encode(secret()), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(value)));
  return btoa(String.fromCharCode(...mac)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}

export async function getUser(request: Request): Promise<{ id: string } | null> {
  const raw = (request.headers.get("cookie") ?? "").split(/;\s*/).find((c) => c.startsWith(`${COOKIE}=`));
  if (!raw) return null;
  const value = decodeURIComponent(raw.slice(COOKIE.length + 1));
  const dot = value.lastIndexOf(".");
  const id = value.slice(0, dot);
  return dot > 0 && (await sign(id)) === value.slice(dot + 1) ? { id } : null;
}

export async function sessionCookie(request: Request, id: string) {
  const secure = new URL(request.url).protocol === "https:" ? "; Secure" : "";
  return `${COOKIE}=${encodeURIComponent(`${id}.${await sign(id)}`)}; Path=/; HttpOnly; SameSite=Lax${secure}`;
}

export const clearedCookie = `${COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`;
```

A `POST /api/login` endpoint sets `sessionCookie(request, name)` with `Set-Cookie`, `GET /api/me`
returns the user (or `null`) so the page knows whether to show sign-in, and `POST /api/logout`
clears the cookie and calls `db.deauthorizeStream({ userID })`. When the app needs to name other
users (to share or assign to them), upsert an `app_user(id TEXT PRIMARY KEY)` row on login and
check it in the write.

### The page's client

Create one live client per signed-in page, close it on sign-out, and give it to the page's
components with `RindleProvider`:

```tsx
import { useEffect, useState, type ReactNode } from "react";
import { createClient, RindleProvider, type RindleClient } from "@rindle/react";

function useStreamClient(): RindleClient | null {
  const [db, setDb] = useState<RindleClient | null>(null);
  useEffect(() => {
    const client = createClient({ base: "/api/rindle", stream: process.env.RINDLE_STREAM_URL! });
    // The client opens a WebSocket, so it is made after mount and closed on unmount.
    setDb(client); // eslint-disable-line react-hooks/set-state-in-effect
    return () => client.close();
  }, []);
  return db;
}

export function SignedIn({ children }: { children: ReactNode }) {
  const db = useStreamClient();
  return db ? <RindleProvider client={db}>{children}</RindleProvider> : null;
}
```

Render `<SignedIn key={user.id}>` around the signed-in part of the page, so a different user gets
a fresh client. Inside it, `useQuery("notes")` or `useQuery("poll", { id })` names a query;
the hook adds it on mount and removes it on unmount, batching each tick's changes into one request.

## Instant UI: preloading and optimistic writes

Build interactive pages so that nothing the user does waits on the network: switching between
things the user is likely to switch between shows rows at once, and the user's own writes show
the moment they are made. `@rindle/react` has no cache and no mutation layer; both come from how
you shape the queries and a little state in the page.

**Each `useQuery` is its own live query.** Two components asking for the same name and args are
two queries, and a component that mounts, or whose args change, waits a round trip for its rows.
So read a query once, high enough in the tree, and pass the rows down.

### Preload with the Query's Shape

Put what the user switches between into the query they already have open, with a nested `WITH`
and a per-parent `LIMIT`. For a chat, the channel list carries each channel's newest 50 messages:

```sql
SELECT id, name FROM channel
WHERE EXISTS (SELECT 1 FROM member WHERE member.channel_id = channel.id AND member.user_id = ?)
ORDER BY name
WITH messages OF message ON channel_id = id (ORDER BY id DESC LIMIT 50)
```

```tsx
const { rows: channels } = useQuery<Channel>("channels");
const channel = channels.find((c) => c.id === activeID); // switching is a state change, not a fetch
```

Every message write updates that one query, and switching channels never asks the server for
anything. Load older history ("scroll up") with a separate keyset query for the open channel only.
Other cases have the same shape: a list of auctions with each one's latest bids, a game lobby with
each game's moves, a poll list with each poll's options.

Two limits of nested rows to design for. **A nested row carries every column of its table**:
there is no column list inside `WITH`, so a column some users may not see (a quiz's correct
answer, a sealed bid) goes in a table of its own that only the queries for those who may see it
read. And **a count or sum can't go inside a `WITH`**, only in the outer `SELECT` list, so a
nested row that needs one stores it as a column, updated in the same `transaction` as the rows it
counts (`option.votes` next to each `vote` insert).

When the next view doesn't fit the open query (a different shape, or too many rows to carry for
every item), **mount it before it is shown**: render the likely next view's component with
`hidden` (the next question's board, the item under the pointer), and un-hide it on the switch. A
mounted `useQuery` already has its rows, so the switch is instant. Keep the component mounted
across the switch (same position in the tree, same `key`); a remount, or a change of its args,
waits again.

Preload only what this user may see now. `queryFor` still decides, so a preloaded query for
something hidden (the next trivia question before it opens, a sealed bid) must be refused or must
leave out the secret columns.

### Optimistic Writes

Show a write before the server confirms it, and let the live query take over once it lands:

1. **Mint the row's id in the page** (`crypto.randomUUID()`, or a sortable id for things ordered by
   id) and send it to the endpoint, which writes the row with that id after its checks.
2. **Keep the write in page state as pending**, and render it from there, marked ("Sending…",
   dimmed).
3. **Drop the pending entry once the live rows contain its id.** The endpoint's reply is not the
   signal: the row can arrive on the stream before or after it.
4. **On failure, keep it and say so**, with a retry button. A refusal (a bid below the current
   price, a move out of turn) removes it and shows why.

```tsx
type Pending = { id: string; body: string; failed?: boolean };

function useSend(channelID: string, live: readonly { id: string }[]) {
  const [pending, setPending] = useState<Pending[]>([]);
  // Confirmed rows replace their pending copies.
  const shown = pending.filter((p) => !live.some((m) => m.id === p.id));
  async function send(body: string, id = crypto.randomUUID()) {
    setPending((ps) => [...ps.filter((p) => p.id !== id), { id, body }]);
    const res = await fetch(`/api/channels/${channelID}/messages`, {
      method: "POST",
      body: JSON.stringify({ id, body }),
    }).catch(() => null);
    if (!res?.ok) setPending((ps) => ps.map((p) => (p.id === id ? { ...p, failed: true } : p)));
  }
  return { pending: shown, send };
}
```

Keep the pending list per channel (or per thing written to). For changes to existing rows (a
vote, a toggle, a bid, a chess move), keep an override keyed by the row's id, render the override
while it exists, and drop it once the live row shows the new value or the request fails. For a
row that moves through states, record what the override was based on and drop it when the live
row has moved past that (a game's `move_count` above the one the move was made at). The endpoint
stays the authority: a refused write reverts on screen. Reads the user causes count too: mark a
channel read in page state when they open it, or its unread badge stays until the write lands.

A write that is safe to retry should be idempotent by its id (`INSERT … ON CONFLICT DO NOTHING`),
so a retry after a timeout cannot write twice.

## Schema and migrations

Migrations run from your side, never from the page. Keep them in a module and run it with a script
before starting the app (and against production's `RINDLE_URL` when deploying):

```ts
// scripts/migrate.ts — run with: node --env-file=.env scripts/migrate.ts
import { createClient } from "@rindle/api";

const db = createClient(); // reads RINDLE_URL and RINDLE_API_TOKEN
// Applied once per name, ever; later runs are no-ops.
await db.migrate("0001_init", `
  CREATE TABLE note (
    id    TEXT NOT NULL PRIMARY KEY,
    owner TEXT NOT NULL,
    title TEXT NOT NULL
  );
  CREATE INDEX note_owner ON note (owner);
`);
db.close();
```

Node 22.18 or later runs `.ts` files directly.

- `migrate(name, sql)` applies the SQL once per name and records it. A name that was already
  applied does not run again, even if its SQL changed. To change the schema, add a migration with
  a new name. Never edit an applied one. To start over in development, ask the user first, then run
  `npx rindle reset --yes`: it erases every table, row and migration, and keeps the URL and
  token, so the migrations apply again.
- `migrate` takes schema statements only: `CREATE`/`DROP TABLE`, `ALTER TABLE … ADD`/`DROP`/`RENAME
  COLUMN`, `ALTER TABLE … RENAME TO`, `CREATE`/`DROP INDEX`. Seed data with ordinary writes that
  are safe to repeat (`INSERT … ON CONFLICT DO NOTHING`).
- **Every table needs a primary key, and your app supplies its values.** There is no
  `AUTOINCREMENT` and no rowid — the store assigns no keys, because a keyed write names its own.
  Use a `TEXT` key: `crypto.randomUUID()`, a ulid, or an id you derive from the data. A counter
  row you read and write by key inside a transaction works when ids must be dense.
- `IF NOT EXISTS` / `IF EXISTS` are refused: the migration's name is already the idempotency key,
  and re-sending it is already a no-op, so the clause can only hide a mistake.
- `UNIQUE`, `CHECK`, `FOREIGN KEY` and `REFERENCES` are refused, because nothing downstream
  enforces a constraint — accepting the word would promise a check no store makes. Enforce
  uniqueness by making the unique thing the primary key, and check the rest in your endpoints.
- Column types decide what JavaScript values you get back in live rows:

  | Declare | Live rows give you |
  | --- | --- |
  | `TEXT` | `string` |
  | `INTEGER`, `REAL`, `NUMERIC` | `number` (a double — `INTEGER` is **not** exact here) |
  | `BOOLEAN` | `boolean` (write `true`/`false` or `1`/`0`) |
  | `JSON` | the JSON text, a `string`: `JSON.parse` it (write `JSON.stringify(value)`) |

  `BIGINT` and `INT8` are the exact 64-bit integer, and a live query cannot select one yet — so
  keep ids and counters you query on `TEXT` or `INTEGER`. `BLOB` columns, `COLLATE`, generated
  columns, expression defaults, expression indexes and in-place retypes are refused; to change a
  column's type, add a new column, rewrite the data, and drop the old one.
- `NOT NULL` works. `DEFAULT` is refused in `CREATE TABLE` (an `INSERT` that leaves a column
  out stores `NULL` there, so write the value) and taken only by `ALTER TABLE … ADD COLUMN`, where it fills the existing rows. A live query with `ORDER BY … LIMIT` wants an index on its filter
  columns followed by its `ORDER BY` columns, in the same `ASC`/`DESC` directions. To find a slow
  query, filter the dashboard's logs for `slow-query` or `slow-advance`.
- **Leave the primary key out of an index and out of the end of `ORDER BY`.** Every index and
  every query order ends with the key, added for you in the direction of the last column. So
  `ORDER BY score DESC` runs as `score DESC, id DESC`, and `CREATE INDEX player_rank ON player
  (game_id, score DESC)` streams it. Spelling the key against that direction
  (`(game_id, score DESC, id)`, or `ORDER BY score DESC, id ASC`) is refused in a migration and
  sorts in memory in a query; spelling it in the same direction is harmless.
- Set timestamps from the app (`Date.now()` as a param) rather than with SQL time functions.

## Writes

Write endpoints run SQL with the server's `db` (from `src/server/rindle.ts`, above). Writes are durable
when the promise resolves, and every affected live query updates right after, for every user who
can see the rows.

**An `INSERT` names its own primary key**, and an `UPDATE`/`DELETE` takes a `WHERE` over the
table's own columns:

```ts
// One statement. `params` bind to `?` placeholders in order.
const pollId = crypto.randomUUID();
await db.execute({
  sql: "INSERT INTO poll (id, owner, question, created_at) VALUES (?, ?, ?, ?)",
  params: [pollId, user.id, question, Date.now()],
});

// Several statements, atomically: all or none.
await db.batch([
  { sql: "INSERT INTO option (id, poll_id, label) VALUES (?, ?, ?)", params: [crypto.randomUUID(), pollId, "Yes"] },
  { sql: "INSERT INTO option (id, poll_id, label) VALUES (?, ?, ?)", params: [crypto.randomUUID(), pollId, "No"] },
]);

// A write that depends on a read: one transaction. See below for retrying a conflict.
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] ?? 0);
  if (stock < 1) throw new Error("sold out");             // throwing rolls back
  await tx.execute({ sql: "UPDATE item SET stock = ? WHERE id = ?", params: [stock - 1, id] });
});
```

Accepted: `INSERT … VALUES` (one tuple or several), `ON CONFLICT DO NOTHING` / `INSERT OR IGNORE`,
`ON CONFLICT DO UPDATE SET c = excluded.c` / `INSERT OR REPLACE`, and `UPDATE`/`DELETE` with a
`WHERE` built from `= != <> < <= > >=`, `IS NULL`, `IS NOT NULL`, `IN`, `NOT IN`, `BETWEEN`,
`AND`, `OR`, `NOT` and parentheses, to any depth — each comparison between a column and a value.
A `DELETE` with no `WHERE` empties the table. Everything else is refused with the rewrite in the
message. The common surprises:

- **An ownership guard belongs in the `WHERE`.** `UPDATE note SET … WHERE id = ? AND owner = ?`
  works, and `rowsAffected === 0` is your `403`/`404`: the predicate is evaluated by the writer
  against the rows the statement commits against, so it cannot be raced. The user's id always
  comes from the session, never from the request body or URL.
- **`SET` takes values, not expressions.** `SET stock = stock - 1` is refused, and so is
  `CASE WHEN`: read, compute, write back, as above. Counters therefore need the transaction, not
  a clever statement.
- **A `WHERE` compares a column with a value.** No `LIKE`, no subquery (`IN (SELECT …)`), no
  `a = b` between two columns, no `INSERT … SELECT`. Select the rows you mean — reads are not
  restricted — then write them.
- **`NULL` follows SQL.** `WHERE tag != 'a'` does not match a row whose `tag` is `NULL`, and
  `WHERE tag = NULL` matches nothing: `IS NULL` is the only comparison that reaches a null.
- **A `WHERE` naming the whole primary key is a key lookup**, whatever else it says — so the
  guard above is a single-row write. Anything else reads **every row** of the table: no secondary
  index is used yet, so `DELETE FROM event WHERE at < ?` scans `event` even with an index on `at`.
  Good for a sweep, wrong for a hot path. Put a key in the `WHERE` where you can.
- **A plain `INSERT` of a key that exists fails** (`schema violation: an add of a primary key that
  exists`). Use `ON CONFLICT DO NOTHING` or `DO UPDATE` when the row may be there.
- **No `RETURNING`.** A write answers with its watermark, not with rows: read the row back if you
  need it. `lastInsertRowid` is always `null` for the same reason.
- **`ON CONFLICT` takes no target.** An upsert conflicts on the primary key and nothing else, so
  write `ON CONFLICT DO NOTHING`, not `ON CONFLICT (id) DO NOTHING`, and give `DO UPDATE` every
  non-key column, since an upsert replaces the whole row.
- `rowsAffected` is the rows the statement **addressed**: the rows a `WHERE` matched, or 1 for a
  statement addressed by key whether or not that row was there. `execute` and `batch` refuse
  schema statements; use `migrate`.
- `batch` is one transaction: an error rolls the whole batch back. A statement that matches no rows
  is not an error, so use `transaction` when a later write must depend on an earlier one's count.
- A `transaction` reads a private snapshot, and other writes go on while it is open. At commit,
  if another write changed what it read, it throws an error whose `code` is
  `"TRANSACTION_CONFLICT"` and nothing is applied. `db.transaction` does not rerun your callback,
  so wherever two users can race for the same row (a bid, a move, a vote count), retry it:

  ```ts
  async function retrying<T>(fn: () => Promise<T>, attempts = 10): Promise<T> {
    for (let i = 1; ; i++) {
      try {
        return await fn();
      } catch (e) {
        if ((e as { code?: string }).code !== "TRANSACTION_CONFLICT" || i >= attempts) throw e;
        await new Promise((r) => setTimeout(r, Math.random() * 20 * i));
      }
    }
  }

  await retrying(() => db.transaction(async (tx) => { /* read, check, write */ }));
  ```

  The callback must be safe to run again, so do its checks inside it, against what `tx` reads.
- A transaction closes after five seconds with no operation, and 30 seconds after it began. Do any
  slow work (an API call, an LLM) outside it. Read through `tx` to see the transaction's own
  writes; `db.read` sees only committed state, and does not wait for the transaction.
- Rindle doesn't apply writes optimistically: a live query shows a change when it arrives on the
  stream, a round trip later. Show the user's own writes at once from page state (see "Instant
  UI"). A test that asserts the confirmed state should wait for it; for a checkbox bound to a
  live row, Playwright's `check()` fails ("did not change its state"), so `click()` and then wait
  for it to become checked.

## Live SQL: what a live query can be

The SQL `queryFor` returns (sent with `db.subscribeOps`) and `db.query` (in Node) accept a
SQLite `SELECT` in the subset below, which the database keeps up to date incrementally. Anything
outside it is refused at once with an error that names the problem: that query's op fails with
code `compile`, and the page sees it as the query's `error`. A refused query is a modeling question, not a bug to work around with
polling.

**Only the selected columns reach the page.** A column list must include the primary key and every
`ORDER BY` column (the compiler refuses one that doesn't). Select exactly what this user may see; a
column used only in `WHERE` is never sent.

**Supported:**

- `SELECT *` or `SELECT col, col` (plain column names; no `AS` renames, no expressions), including the
  primary key and every `ORDER BY` column.
- `WHERE` comparing a column to a literal or a `?` param: `=`, `!=`, `<`, `<=`, `>`, `>=`,
  `<>`, `IS NULL`, `IS NOT NULL`, `LIKE`, `NOT LIKE`, `ILIKE`, `IN (?, ?)`, `NOT IN (...)`,
  `BETWEEN ? AND ?`, `IS TRUE`/`IS FALSE`, combined with `AND`, `OR`, and parentheses. The full
  list is at https://www.rindle.sh/sql.
- `ORDER BY` any columns, `ASC`/`DESC`, and `LIMIT n`. A query that shows a list should have a
  `LIMIT`.
- `EXISTS (SELECT 1 FROM child WHERE child.parent_id = parent.id AND ...)` and `NOT EXISTS`. This
  is how permission rules read other tables (shares, team membership).
- **Nested results (instead of JOIN).** A trailing `WITH` clause attaches related rows to each
  result row:

  ```sql
  SELECT * FROM poll WHERE id = ?
  WITH options OF option ON poll_id = id (ORDER BY id)
  ```

  gives `[{ id, question, ..., options: [{ id, poll_id, label }, ...] }]`. The syntax is
  `WITH [ONE] <field> OF <table> ON <column in that table> = <column in the outer table> (<body>)`.
  The body can hold `WHERE`, `ORDER BY`, `LIMIT`, and further `WITH` clauses, and may be empty
  `()`. `WITH ONE` gives one object or `null` instead of an array, for a to-one link. Several
  `WITH` clauses can follow one another; nothing else may follow the first `WITH`.
- **Counts and sums per row**, as a correlated subquery in the column list:

  ```sql
  SELECT id, label, (SELECT count(*) FROM vote WHERE vote.option_id = option.id) AS votes
  FROM option WHERE poll_id = ? ORDER BY id
  ```

  `count(*)`, `sum(col)`, and `avg(col)` work this way, and the subquery can carry its own `WHERE`
  of column-to-literal or column-to-param comparisons. It cannot nest another subquery, call a
  function such as `COALESCE`, or compare against a column of a third table. This is the one place
  `AS` is allowed.

**Refused, and what to do instead:**

| Refused | Instead |
| --- | --- |
| `JOIN` of any kind | `WITH` / `WITH ONE` (nested rows), or `EXISTS` to filter |
| Top-level `count(*)`, `GROUP BY`, `HAVING` (allowed only inside `EXISTS`) | A correlated count on a parent row. For a global total, keep a one-row table such as `stats`, or count a small live result in JavaScript. |
| `DISTINCT`, `UNION`, CTEs (`WITH x AS`), subqueries in `FROM`, window functions | Model a table that holds what you need, or nest with `WITH` |
| `OFFSET` | Keyset paging: `WHERE (created_at, id) > (?, ?) ORDER BY created_at, id LIMIT n`, or for descending order `WHERE created_at < ? OR (created_at = ? AND id < ?)` |
| Expressions or functions anywhere (`created_at > ? - 60000`, `lower(name)`, `now()`) | Compute the value in JavaScript and pass it as a param. A param is fixed for the life of the query. |
| `col AS alias`, `*` mixed with expressions | Plain column names; rename in JavaScript |
| Comparing two columns (`a < b`) | Store the comparison's result in its own column when you write the row |
| Named params (`:id`), array params | Positional `?` (or `?1`, `$1`), one per value |

**This subset is the whole `SELECT` surface, not just the live one.** A one-shot read — `db.read`,
or a `SELECT` through `db.execute` — is compiled and run by the same engine, so it refuses the
same shapes with the same message. There is no larger SQL plane to fall back to: compute what the
subset cannot in JavaScript, over rows it can return. The two differ only in shape: `db.read`
answers the nested tree, and `db.execute` answers a rectangle and refuses a query with a `WITH`
clause by name.

## Patterns for common apps

- **Who can see what** is the query's `WHERE`: `owner = ?`, `OR EXISTS (SELECT 1 FROM share ...)`,
  team membership through `EXISTS`. Pick a different query per role in `queryFor`. More examples
  are on the architecture page.
- **Revoking access is live.** Deleting a share or a membership row removes the rows from the other
  user's open page. For rules outside the data (sign-out, a ban), call
  `db.deauthorizeStream({ userID })`.
- **Share links.** Put the id in the URL and pass it as an arg (`useQuery("poll", { id })`);
  `queryFor` still checks that the user may see it. Don't ask for a query the user can't have yet
  (before they join a game, say): pass `null` as the name until they can, or the hook reports the
  refusal as an error. When args change to a different thing (the next quiz question), pass
  `{ keepPrevious: false }`, or the old rows show until the new ones arrive.
- **Votes, likes, reactions.** One row per user per thing, keyed by the pair
  (`PRIMARY KEY (option_id, user_id)`, or a `TEXT` id you compose from both), and a correlated
  `count(*)` on the parent for the totals. Toggle with `INSERT … ON CONFLICT DO NOTHING` and
  `DELETE … WHERE` the whole key. The composed key is what gives you "at most once" without a
  `UNIQUE` constraint.
- **Chat.** Carry each channel's newest messages in the channel list's query (see "Instant UI"),
  send messages optimistically, show public channels to everyone with
  `kind = 'public' OR EXISTS (SELECT 1 FROM member …)`, and use `ORDER BY id DESC LIMIT n`, then reverse in JavaScript to
  display oldest first. Give
  messages sortable ids (a ulid, or `${Date.now()}-${crypto.randomUUID()}`) since there is no
  rowid to order by. Index it as `CREATE INDEX message_channel ON message (channel_id)`: the key `id`
  follows on its own, and `WHERE channel_id = ? ORDER BY id DESC` reads it backwards.
- **Per-user unread counts.** Keep a `message_count` on the channel, updated in the same
  `transaction` as each insert, and a `read_state(channel_id, user_id, read_count, PRIMARY KEY
  (channel_id, user_id))` row set to the channel's count when the user views it. Then
  `SELECT * FROM channel ORDER BY name WITH ONE mine OF read_state ON channel_id = id (WHERE user_id = ?)`
  gives every unread count as `message_count - (mine?.read_count ?? 0)`.
- **Presence.** Each page upserts a `presence(id, name, last_seen)` row through an endpoint every
  few seconds — `ON CONFLICT DO UPDATE SET last_seen = excluded.last_seen`. Live-query the whole
  (small) table and filter `last_seen > Date.now() - 15000` in JavaScript on a timer.
- **Agents and workers.** A `job` table with a `status` column is the queue. Endpoints insert
  `pending` rows and the page live-queries their status; a Node worker claims a row in a
  transaction and writes results back (see "Node").
- **Derived state.** If a live query needs something the SQL subset cannot compute, compute it when
  you write and store it in a column.
- **Anonymous visitors** ("anyone with the link votes once"). Give each browser a random id in a
  signed HttpOnly cookie, the same way as the sign-in cookie. In Next.js set it in `proxy.ts`
  (middleware) on the first request, and also copy it into that request's `cookie` header, so the
  first server render sees it: a server component can't set cookies.
- **Deadlines and countdowns** (auctions, quiz timers). Store the deadline as a number
  (`Date.now()`-based) and enforce it in the write endpoint against the server's clock; the page
  counts down locally. There is no server timer in a stateless app: when something must happen at
  the deadline (close a question, settle an auction), have pages call an endpoint that checks the
  clock and is safe to call twice, or run a small Node worker. Allow a second or so of grace for
  writes already in flight at the deadline. When the deadline only stops writes (an auction's high
  bidder at the end wins), nothing has to happen at it: the endpoint's check is the whole rule.
- **Rows from `execute`** are arrays in column order. To get objects:
  `rows.map((r) => Object.fromEntries(columns.map((c, i) => [c.name, r[i]])))`.

## Node: scripts, workers, and agents

A Node process on your side of the boundary uses `@rindle/api` directly, with live queries:

```ts
// worker.ts — run with: node --env-file=.env worker.ts
import { createClient } from "@rindle/api";

const db = createClient(); // reads RINDLE_URL and RINDLE_API_TOKEN

const pending = await db.query<{ id: string; prompt: string }>(
  "SELECT id, prompt FROM job WHERE status = 'pending' ORDER BY id LIMIT 10",
);
pending.subscribe(async (jobs) => {
  for (const job of jobs) {
    // Claim it. The claim is one statement: the `status` term makes it a predicate, evaluated by the
    // writer against the row it commits against, so two workers cannot both win.
    const { rowsAffected } = await db.execute({
      sql: "UPDATE job SET status = 'working' WHERE id = ? AND status = 'pending'",
      params: [job.id],
    });
    if (rowsAffected === 0) continue;                               // someone else has it
    const answer = await doTheWork(job.prompt);
    await db.execute({ sql: "UPDATE job SET status = 'done', answer = ? WHERE id = ?", params: [answer, job.id] });
  }
});
// The open live query keeps the process running. Ctrl-C (or db.close()) ends it.
```

The claim is a **conditional update**, which is what makes it safe without a transaction: the
`status = 'pending'` term is evaluated by the writer against the row the statement commits
against, so of two workers reaching the same job exactly one sees `rowsAffected === 1`. Note that
`doTheWork` runs outside any transaction: a transaction held open across an LLM call would hit its
time limit and roll back.

The listener fires immediately with the current rows and again after every change, including the
worker's own, and can run again while an earlier run is still awaiting, so make it safe to repeat.
`await db.read(sql, params)` reads a live-subset query once, as the nested tree; `db.execute` reads
the same query as a rectangle. For streaming output (an LLM answer), update the row as chunks
arrive, batched every 50–100 ms; every viewer's query updates on each write.

## Before you finish

- These checks write rows. If the database came from the user's `.env` and the app already has
  users, it is their production database: ask before writing to it or applying new migrations.
- Check it end to end: run the app, sign in as two users in two browser windows
  (or a normal and a private window), write in one, and watch the other update without a reload.
  Check that each user sees only their own rows.
- Check that it's instant. Slow the write endpoints down (in Playwright,
  `page.route(/\/api\/(?!rindle\/)/, async (r) => { await new Promise((t) => setTimeout(t, 1000)); await r.continue(); })`,
  which leaves the `/api/rindle/` routes alone)
  and check that your own writes still show at once, then turn into confirmed rows. Switch between
  the things you preloaded and check that the rows are on screen by the next
  `requestAnimationFrame` after the click, with no loading state and no request.
- Servers you start in the background: `npm run dev`'s PID is npm's, and killing it leaves Vite
  running on the port. Start `node_modules/.bin/vite dev --port <n>` instead, so the PID you keep
  is the server's.
- Check the boundary: the page's network requests go only to the app's `/api/...` routes and
  Rindle's stream (`/db/stream`; in Playwright that is a `page.on("websocket")` event, not a
  `request`), and no file the browser loads contains the app's SQL or
  `RINDLE_API_TOKEN`. Rindle's public stream address (`RINDLE_URL`'s origin) is in the page by
  design; without a stream token it can read nothing.
- Tell the user how to run it: the migration script, then the app.
- **Deploying.** The app's server environment gets `RINDLE_URL` and `RINDLE_API_TOKEN` plus
  `SESSION_SECRET` (on Cloudflare, `wrangler secret put`). With Cloud Rindle those are the two
  lines `npx rindle deploy` printed. The page is built with `RINDLE_URL`'s origin, so the build
  needs `RINDLE_URL` too. A `wrangler secret put` value exists only when the Worker runs, so give a
  build in Workers Builds or CI `RINDLE_URL` as a build variable; it isn't secret. Run the
  migration script against production before the app.
  See https://www.rindle.sh/cloud.md.

## Troubleshooting

| Symptom | Cause and fix |
| --- | --- |
| `fetch failed` in the server | `RINDLE_URL` is wrong. Check it against what `npx rindle deploy` printed. |
| Every Rindle call fails with `522` and a Cloudflare HTML page as the message | Nothing serves that address yet: the database is still in the queue (`npx rindle deploy` says where it stands), or the app id in `RINDLE_URL` is mistyped. |
| `pass url, or set RINDLE_URL` | The server process has no `RINDLE_URL`: Next.js reads `.env` from the app directory; a Worker needs `.dev.vars` (or `CLOUDFLARE_INCLUDE_PROCESS_ENV=true`) and `nodejs_compat`. |
| Worker: `Cannot perform I/O on behalf of a different request` or `Disallowed operation called within global scope` | I/O at module scope. Create clients there, but call them only inside a request. |
| `unsupported: …` on a write | A shape with no operation to compile onto: an expression in a `SET`, a `LIKE`, a subquery, `INSERT … SELECT`. The message names the rewrite. See "Writes". |
| `unsupported: \`RETURNING\`` / `unsupported: \`ON CONFLICT (id)\`` | Read the row back instead; drop the conflict target. |
| `expected a literal value, found \`<column>\`` | A `SET` expression over a column. Read, compute in JavaScript, write the value back. |
| `the INSERT does not name \`<table>\`'s key column` | Generate the id in the app and name it in the column list. `AUTOINCREMENT` is not supported yet. |
| `unsupported: \`AUTOINCREMENT\`` in a migration | Declare a `TEXT PRIMARY KEY` and mint ids with `crypto.randomUUID()`. |
| Query `error` has `status` `401` or `403` | Your query route refused it: the session cookie is missing (`401`), or `queryFor` refused this user (`403`). A `401` also comes from Rindle when the server's `RINDLE_API_TOKEN` is missing or wrong; `migrate` fails the same way. |
| Query `error` has `code` `compile` (`unsupported: ...`, `live queries must select ...`) | The SELECT is outside the live subset, or its column list leaves out the primary key or an `ORDER BY` column. See "Live SQL". |
| Live query never leaves `loading` | The browser can't reach the `stream` address the page was built with (check that `RINDLE_URL` was set when the page was built), or a proxy in front of Rindle buffers the stream. |
| `unsupported: \`1\` in a select list` | `SELECT 1` works only inside `EXISTS`. A plain read lists real columns: `SELECT user_id FROM member WHERE …`. |
| `no such table` | Run the migration script before the app. If you added the table by editing an applied migration, that edit never ran: put it in a migration with a new name. |
| `410 TRANSACTION_CLOSED` | A transaction sat five seconds with no operation, or ran past 30 seconds. Do the slow part outside it. |
| `TRANSACTION_CONFLICT` | Another write changed a row the transaction read. Nothing was applied: run the transaction again (see "Writes"). |
| `503` with `Retry-After` | The database is starting, or 32 writes are already in flight. Retry. |
| Next.js dev: `Blocked cross-origin request to Next.js dev resource`, page never hydrates | You opened the page at `127.0.0.1`. Open `http://localhost:<port>`, or add the host to `allowedDevOrigins` in `next.config.ts`. |
| Vite dev prints `Unable to fetch the Request.cf object` | A network proxy blocks Cloudflare's lookup. Harmless locally. |

## API summary

The architecture and React pages show each of these in context.

```ts
import { createClient } from "@rindle/api";                              // server + Node
import { createSSRClient } from "@rindle/react/server";                  // server render
import { createClient as createPageClient, RindleProvider, useQuery } from "@rindle/react"; // browser

// Server or Node: one client, reading RINDLE_URL and RINDLE_API_TOKEN
const db = createClient();                                   // or createClient({ url, apiToken })

// SQL
db.execute(stmt): Promise<StatementResult>                   // { columns, rows, rowsAffected, lastInsertRowid }
//   columns: { name, decltype }[]; rows: arrays in column order (use db.read for objects)
db.batch([stmt, ...]): Promise<StatementResult[]>             // one transaction
db.transaction(async (tx) => ...)                            // tx.execute / tx.batch; throwing rolls back
db.migrate(name, sql): Promise<{ applied: boolean }>
// stmt is "SELECT …" or { sql, params }; params is an array for `?` or an object for `:name`.

// Queries
db.query<Row>(sql, params?): Promise<LiveQuery<Row>>         // data, subscribe(fn), resultType, destroy()
db.read<Row>(sql, params?): Promise<Row[]>                   // once, as the nested tree

// The page's two routes
db.authorizeStream({ clientID, userID?, streamToken? }): Promise<{ streamToken }>
db.subscribeOps({ clientID, userID?, streamToken, ops }): Promise<OpResult[]>
db.deauthorizeStream({ userID?, clientID? }): Promise<{ ended: number }>
db.close()

// The query route is under "Project setup". queryFor returns { sql, params?: QueryParam[] } (or
// { query } for a builder query) and throws to refuse. Types: import type { QueryParam, SubscribeOp,
// OpResult } from "@rindle/api".

// Browser
const live = createPageClient({ base: "/api/rindle", stream: process.env.RINDLE_STREAM_URL! });
<RindleProvider client={live}>…</RindleProvider>
useQuery<Row>(name | null, args?, { keepPrevious? }): { rows: readonly Row[]; status: "loading" | "complete" | "error"; error?: Error }
live.close()
```

`status` is `"loading"` until the first result, then `"complete"`. Show "no notes yet" only when
`status === "complete"`. `rows` are plain objects, a new array on every change; don't mutate them.
Changing the name or args swaps the query (args compare by value; the old rows stay, with
`status: "loading"`, until the new query completes); unmounting removes it.
