# Database

With `"database": true` in the [manifest](https://boring-cloud.app/docs/manifest.md), the backend gets `env.APP_DB`: one private SQL database for this app, based on SQLite (Cloudflare D1). The platform creates it at the first release that asks for it. No other app can reach it.

## Queries

```js
// One row, or null
const row = await env.APP_DB.prepare("SELECT * FROM items WHERE id = ?").bind(id).first();

// Several rows
const { results } = await env.APP_DB.prepare("SELECT * FROM items WHERE status = ? ORDER BY id DESC LIMIT 100")
  .bind("open")
  .all();

// A change
const { meta } = await env.APP_DB.prepare("UPDATE items SET status = ? WHERE id = ?").bind("done", id).run();
if (meta.changes === 0) return json({ error: "Not found." }, 404);

// Several changes: all of them, or none
await env.APP_DB.batch([
  env.APP_DB.prepare("INSERT INTO items (title) VALUES (?)").bind(title),
  env.APP_DB.prepare("INSERT INTO log (text) VALUES (?)").bind("item added"),
]);
```

**Every value goes through `bind`.** Never put a value in the text of a query. Column names and sort orders cannot be bound: choose them from a fixed list in your code.

`undefined` cannot be bound. Use `null`. Booleans are stored as `0` and `1`. Store dates as ISO text, such as `new Date().toISOString()`.

## Create tables

There is no migration step. Create tables when a request arrives, in a way that can run again without harm:

```js
let ready; // once per running copy of the module
const ensureSchema = (db) =>
  (ready ??= db
    .batch([
      db.prepare(`CREATE TABLE IF NOT EXISTS items (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        status TEXT NOT NULL DEFAULT 'open',
        created_by TEXT NOT NULL,
        created_at TEXT NOT NULL
      )`),
      db.prepare("CREATE INDEX IF NOT EXISTS items_by_status ON items (status, id)"),
    ])
    .catch((e) => {
      ready = undefined; // try again on the next request
      throw e;
    }));
```

Call `await ensureSchema(env.APP_DB)` before the first query of a request. Do not call it for the health check.

## Change tables

Data outlives code. A new release, and a return to an old one, both use the same data. So:

- **Only add.** New tables, or new columns with a default value.
- Never drop or rename a column, and never rewrite existing rows in a way the previous release cannot read.

```js
const addColumn = async (db, sql) => {
  try {
    await db.prepare(sql).run();
  } catch (e) {
    if (!/duplicate column/i.test(String(e))) throw e;
  }
};
await addColumn(env.APP_DB, "ALTER TABLE items ADD COLUMN priority TEXT NOT NULL DEFAULT 'normal'");
```

## Limits that surprise

| Limit                                           | What to do                                                        |
| ----------------------------------------------- | ----------------------------------------------------------------- |
| 100 values bound in one query                   | split a long list into several statements in one `batch`          |
| a `LIKE` pattern of 50 bytes                    | search with `instr(lower(title), lower(?)) > 0`                   |
| 2 MB for one row or text                        | put large content in [files](https://boring-cloud.app/docs/files.md) and keep its name here |
| no `BEGIN` and `COMMIT`                         | `batch`, which is one transaction                                 |
| 50 outside calls per request, each query counts | `batch` and joins, never one query per row in a loop              |
| 10 GB per database                              | enough for records, not for files                                 |

## Two people at the same time

Put the condition in the change itself, instead of reading first and writing after:

```js
const { meta } = await env.APP_DB.prepare("UPDATE slots SET taken_by = ? WHERE id = ? AND taken_by IS NULL")
  .bind(user.id, slotId)
  .run();
if (meta.changes === 0) return json({ error: "Someone else just took this slot." }, 409);
```

## What is not offered

- Access from outside the app: no SQL console, no connection address, no import tool. To load existing data, add an import to the app, for example by pasting CSV.
- Restoring old data. A rollback changes code only. If people can delete things that matter, mark them as deleted instead of removing the row.
