> ## Documentation Index
> Fetch the complete documentation index at: https://fairyfly.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# SQLite API

> Database reference — open, query, write, transactions, and introspection.

`Database` is global — no import, no package. One file per database, synchronous calls, WAL mode on, 5s busy timeout by default.

## Permissions

`Database.open` touches the filesystem, so on-disk databases need both
`read` and `write` grants:

| Check | Flag | Why |
| - | - | - |
| Database file | `--allow-read` **and** `--allow-write` | SQLite opens read/write and may create the file |
| Parent directory | `--allow-write` | WAL and `-shm` siblings are created next to the database |

```sh theme={null}
ff notes.js --allow-read=notes.db --allow-write=.
```

* `:memory:` is exempt — no file is touched, so no flags are needed.
* Both file grants are required even for a query-only workload: the handle is
  opened with `SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE`.
* A write scope naming only the database **file** is not enough. SQLite writes
  `notes.db-wal` and `notes.db-shm` beside it, so the containing directory
  must be writable too.
* Relative paths resolve against the **current** cwd; scopes are resolved
  against the **launch** cwd and never move. If you `process.chdir()` before
  opening, the path lands in the new directory but must still fall inside a
  scope captured at startup.
* Denial happens before `sqlite3_open`, and the error is a real `Error`:

```js theme={null}
try {
  Database.open("notes.db");
} catch (e) {
  console.error(e.name, e.code); // PermissionDenied PERMISSION_DENIED
  console.error(e.message);      // Database.open requires --allow-read for 'notes.db'
}
```

The three possible messages are:

```text theme={null}
Database.open requires --allow-read for 'notes.db'
Database.open requires --allow-write for 'notes.db'
Database.open requires --allow-write for '.'
```

The third uses the parent directory exactly as derived from the path passed to
`open` (`.` when there is no directory component).

Full model: [Permissions](https://fairyfly.dev/concepts/permissions.md).

## Quick look

```js theme={null}
// notes.js
const db = Database.open("notes.db");
db.execNoArgs(`CREATE TABLE IF NOT EXISTS notes (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  text TEXT NOT NULL
)`);

db.exec("INSERT INTO notes (text) VALUES (?)", ["buy milk"]);
console.log(db.rows("SELECT id, text FROM notes"));
// [ { id: 1, text: "buy milk" } ]

db.close();
```

```sh theme={null}
ff notes.js --allow-read=notes.db --allow-write=.
```

## `Database.open(path)`

```js theme={null}
const db = Database.open("app.db");
const mem = Database.open(":memory:");
```

Opens (creating when missing) and returns the handle. Every open enables `PRAGMA journal_mode=WAL` and a 5000ms busy timeout — override the latter per handle with `busyTimeout(ms)`.

Paths must be non-empty, must not contain NUL bytes, and `file:` URI filenames are not supported (they throw a `TypeError`).

> [!WARNING]
>
> The path is relative to the process cwd. `Database.open("app.db")` in `ff start` lands next to where you launched, not necessarily next to your script. Permission scopes are fixed at launch, so launch from the directory you intend to write to, or pass an absolute path that a scope covers.

`:memory:` gets an ephemeral database that disappears when the handle closes. It
is the easiest option for tests and scratch work because it needs no filesystem
permissions.

## Reading: `row` / `rows`

```js theme={null}
const one = db.row("SELECT id, text FROM notes WHERE id = ?", [1]);
console.log(one); // { id: 1, text: "buy milk" } — or null when no row matches

const all = db.rows("SELECT id, text FROM notes ORDER BY id");
console.log(all.length); // 0 when empty — never null
```

| Method | Signature | Returns |
| - | - | - |
| `row` | `row(sql, params?)` | First matching row as an object, or `null` |
| `rows` | `rows(sql, params?)` | Array of row objects (empty array when none) |

Row objects map column names to values. `params` is an array bound to `?` placeholders in order — always prefer placeholders over string interpolation (no escaping bugs, no injection). Each `Database` handle maintains a 64-entry prepared-statement cache (with pre-interned column property atoms and automatic eviction on `SQLITE_SCHEMA`). Parameter binding maps 32-bit signed integers to `INTEGER`, other JS numbers (`double`) to `REAL`, strings to `TEXT`, `ArrayBuffer`/`Uint8Array` to `BLOB`, booleans to `0`/`1`, and `null`/`undefined`/`BigInt` to `NULL`.

## Writing: `exec` / `execNoArgs`

```js theme={null}
db.exec("INSERT INTO notes (text) VALUES (?)", ["buy milk"]);
db.exec("UPDATE notes SET text = ? WHERE id = ?", ["buy oat milk", 1]);
db.exec("DELETE FROM notes WHERE id = ?", [1]);
db.execNoArgs("CREATE INDEX IF NOT EXISTS idx_notes_id ON notes (id)");
```

| Method | Signature | Returns |
| - | - | - |
| `exec` | `exec(sql, params?)` | `undefined` — throws the SQLite error message **as a plain string** on failure (not an `Error`) |
| `execNoArgs` | `execNoArgs(sql)` | Same, for statements without parameters (schema, pragmas, indexes) |

SQL errors throw — a bad statement never fails silently. The thrown value is a **plain string**, not an `Error` object:

```js theme={null}
try {
  db.exec("INSERT INTO missing_table VALUES (?)", [1]);
} catch (e) {
  console.error("write failed:", String(e)); // no such table: missing_table
  console.error(typeof e, e instanceof Error); // "string" false — e.message is undefined
}
```

Permission errors are the exception: they are real `Error` objects thrown by
`Database.open`, with `name` and `code` set.

## Introspection: `changes` / `lastInsertRowId`

Both are **methods** — call them with parentheses, right after the write:

```js theme={null}
db.exec("INSERT INTO notes (text) VALUES (?)", ["eggs"]);
console.log(db.lastInsertRowId()); // 2

db.exec("UPDATE notes SET text = ? WHERE id < ?", ["x", 100]);
console.log(db.changes()); // rows touched by that UPDATE
```

| Method | Returns |
| - | - |
| `lastInsertRowId()` | Rowid of the last successful INSERT on this handle |
| `changes()` | Rows modified by the last write statement |

> [!WARNING]
>
> `db.lastInsertRowId` without `()` is the function object, not the id. This bites in `Response.json({ id: db.lastInsertRowId })` — always write `db.lastInsertRowId()`.

## Transactions: `transaction(fn)`

```js theme={null}
db.transaction(() => {
  db.exec("INSERT INTO accounts (name, bal) VALUES (?, ?)", ["a", 100]);
  db.exec("INSERT INTO accounts (name, bal) VALUES (?, ?)", ["b", 100]);
});
```

Semantics: `BEGIN`, then your function runs (called with the db as `this`, no arguments). Throw inside → `ROLLBACK` and the error propagates. Return cleanly → `COMMIT`. The return value of `transaction()` is whatever your function returned:

```js theme={null}
const id = db.transaction(() => {
  db.exec("INSERT INTO notes (text) VALUES (?)", ["atomic"]);
  return db.lastInsertRowId();
});
console.log(id);
```

Failed transfer rolls everything back — no half-writes:

```js theme={null}
try {
  db.transaction(() => {
    db.exec("UPDATE accounts SET bal = bal - 50 WHERE name = ?", ["a"]);
    throw new Error("insufficient funds"); // -> ROLLBACK
  });
} catch (e) {
  console.log("aborted:", String(e), "| a still has:", db.row("SELECT bal FROM accounts WHERE name = ?", ["a"]).bal);
}
```

## Tuning: `busyTimeout` / `close`

```js theme={null}
db.busyTimeout(10000); // wait up to 10s on locked tables (default 5000)
db.close();            // release the handle — queries after this throw
```

Raise the timeout when workers or concurrent writers contend; lower it to fail fast on deadlock-prone flows.

## Practical example: notes API on disk

```js theme={null}
// server.js
const db = Database.open("notes.db");
db.execNoArgs(`CREATE TABLE IF NOT EXISTS notes (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  text TEXT NOT NULL
)`);

http.serve({ port: 3000 }, (url, method, body) => {
  const path = new URL(url, "http://localhost").pathname;

  if (path === "/notes" && method === "GET") {
    return Response.json(db.rows("SELECT id, text FROM notes ORDER BY id"));
  }
  if (path === "/notes" && method === "POST") {
    const data = JSON.parse(body || "{}");
    if (!data.text) return Response.json({ error: "text is required" }, { status: 400 });
    const id = db.transaction(() => {
      db.exec("INSERT INTO notes (text) VALUES (?)", [data.text]);
      return db.lastInsertRowId();
    });
    return Response.json(db.row("SELECT id, text FROM notes WHERE id = ?", [id]), { status: 201 });
  }
  return new Response("not found", { status: 404 });
});
```

```sh theme={null}
ff server.js \
  --allow-read=notes.db \
  --allow-write=. \
  --allow-net=0.0.0.0:3000
curl -X POST http://127.0.0.1:3000/notes \
  -H "content-type: application/json" -d '{"text":"buy milk"}'
# {"id":1,"text":"buy milk"}
curl http://127.0.0.1:3000/notes
# [{"id":1,"text":"buy milk"}]
```

## Troubleshooting

**`no such table: x`** — the `execNoArgs(CREATE TABLE …)` never ran (fresh cwd? different `open` path?). Paths are cwd-relative — log `process.cwd()` when in doubt.

**`Database.open` throws `PermissionDenied`** — check which message you got.
`...requires --allow-read for 'notes.db'` means the file scope is missing;
`...requires --allow-write for 'notes.db'` means the file write scope is
missing; `...requires --allow-write for '.'` means the **parent directory** is
not writable. A common fix is `--allow-read=notes.db --allow-write=.`.

**Caught error has no `.message`** — SQL failures throw plain strings (`typeof e === "string"`), so `e.message` is `undefined` and `e instanceof Error` is `false`. Log `String(e)`. `Database.open` permission failures are real `Error`s and do have `.message`.

**`database is locked`** — contention beat the busy timeout. Raise `db.busyTimeout(ms)`, shorten write transactions, or serialize writers through one handle.

**`id` comes back as source text in JSON** — you passed `db.lastInsertRowId` instead of calling `db.lastInsertRowId()`. Add the parens.

**Queries after `close()` throw** — by design. Open one handle per process (or per worker) and close only at shutdown.

**`transaction requires a function argument`** — you passed a non-function (e.g. the *result* of calling it). Pass the closure: `db.transaction(() => { … })`.

## See also

* [Permissions](https://fairyfly.dev/concepts/permissions.md) — flags, scopes, denial contract
* [Postgres API](https://fairyfly.dev/api/postgres.md) — network database client
* [API overview](https://fairyfly.dev/api/overview.md) — every injected global
* [Limitations](https://fairyfly.dev/reference/limitations.md) — every hard cap


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.