# SQLite



SQLite gives a Serverless App a small relational database with nothing to
configure: no connection string, no credentials, no client library. Use it for
an App's own data, such as users, posts, settings, or a job queue. Use
[managed Postgres](/docs/ccp/database) when you need more than 64 MB, a
database shared by several Apps, or access from outside the App.

## Quickstart [#quickstart]

From a linked App directory:

```bash
ccp db create --type sqlite
```

The command prints the database ID. Then query the database from your handler
through the `env.DB` global:

```ts
export async function handler(request: Request): Promise<Response> {
  await env.DB.query(
    "CREATE TABLE IF NOT EXISTS visits (id INTEGER PRIMARY KEY, path TEXT NOT NULL)",
  );
  await env.DB.query("INSERT INTO visits (path) VALUES (?)", [
    new URL(request.url).pathname,
  ]);
  const [{ total }] = await env.DB.query("SELECT COUNT(*) AS total FROM visits");
  return Response.json({ total });
}
```

```bash
ccp deploy
curl https://abc123.clusterbase.dev/
# {"total":1}
```

For a complete App with a schema, an API and a page, see
[Build a web app with SQLite](/docs/ccp/sqlite-web-app).

## Bind a Database [#bind-a-database]

`ccp db create --type sqlite` binds one database to the linked App. Outside the
linked directory, pass `--app-id <app-id>`. Running it again for the same App
returns the existing database ID. `--name`, `--org-id`, and `--network` apply
only to Postgres and are rejected for SQLite.

A running deployment may take a few seconds to receive the binding.

## How It Differs from Postgres [#how-it-differs-from-postgres]

| What you might expect                            | How SQLite works                                                                                                                                             |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| A connection string in `.env`                    | There isn't one. The binding belongs to the App, and `env.DB` is available in every deployment of it.                                                        |
| A database per deployment                        | Preview and production deployments of an App share one database. Make schema changes that the current production code can live with.                         |
| `ccp db exec`, `connect`, `migrate`, and backups | These manage Postgres. Query SQLite from your handler.                                                                                                       |
| A local database in `ccp dev`                    | `env.DB` works only in a deployed App. Under `ccp dev`, calls reject. Test database code on a [preview deployment](/docs/ccp/deploying#preview-deployments). |

## Query from a Handler [#query-from-a-handler]

`env.DB` is a global, like `process.env`. It has two methods.

| Method                       | Returns                                             | Use it for                                             |
| ---------------------------- | --------------------------------------------------- | ------------------------------------------------------ |
| `env.DB.query(sql, params?)` | `Promise<Row[]>`                                    | One statement.                                         |
| `env.DB.batch(statements)`   | `Promise<Row[][]>`, one array of rows per statement | Several statements that must succeed or fail together. |

A row is an object keyed by column name. Statements that return no rows, such
as a plain `INSERT`, resolve to an empty array. Add `RETURNING` to get the
affected rows back:

```ts
const [todo] = await env.DB.query(
  "INSERT INTO todos (title) VALUES (?) RETURNING id, title, done",
  [title],
);
```

### Parameters [#parameters]

Pass values as parameters, never by building SQL strings from user input. Use
`?` placeholders and pass values in order. Parameters and column values are
strings, numbers, or `null`. Store booleans as `0` and `1`, dates as ISO
strings or Unix timestamps, and JSON as text.

### Transactions [#transactions]

`batch` runs its statements in order inside one transaction. If any statement
fails, none of them apply.

```ts
await env.DB.batch([
  { sql: "UPDATE accounts SET balance = balance - ? WHERE id = ?", params: [amount, from] },
  { sql: "UPDATE accounts SET balance = balance + ? WHERE id = ?", params: [amount, to] },
]);
```

Each call is its own transaction, so you can't read a value in one call and
rely on it in a later write. Express the dependency in SQL instead, with a
subquery, `INSERT ... SELECT`, or `ON CONFLICT`.

### TypeScript [#typescript]

Add this declaration to your project's `globals.d.ts` so `env.DB` type-checks:

```ts
type SQLiteValue = string | number | null;
type SQLiteRow = Record<string, SQLiteValue>;

declare const env: {
  DB: {
    query(sql: string, params?: SQLiteValue[]): Promise<SQLiteRow[]>;
    batch(statements: { sql: string; params?: SQLiteValue[] }[]): Promise<SQLiteRow[][]>;
  };
};
```

## Create Your Schema [#create-your-schema]

Create tables from your App, in a statement that is safe to run again:

```ts
let ready: Promise<unknown> | undefined;

function schema() {
  ready ??= env.DB.batch([
    { sql: "CREATE TABLE IF NOT EXISTS todos (id INTEGER PRIMARY KEY, title TEXT NOT NULL, done INTEGER NOT NULL DEFAULT 0)" },
    { sql: "CREATE INDEX IF NOT EXISTS todos_done ON todos (done)" },
  ]).catch((error) => {
    ready = undefined;
    throw error;
  });
  return ready;
}
```

Call `await schema()` before your first query. For changes to a schema that
already holds data, keep an ordered list of migrations as shown in
[Build a web app with SQLite](/docs/ccp/sqlite-web-app#7-change-the-schema-later).

## Limits [#limits]

| Limit                       | Value  |
| --------------------------- | ------ |
| Database size               | 64 MB  |
| Databases per App           | 1      |
| Databases per organization  | 8      |
| Statements per `batch`      | 64     |
| SQL and parameters per call | 256 KB |
| Result size per call        | 1 MB   |

A database still being provisioned counts toward the organization limit, and so
does a database detached by App or Project deletion or a cross-organization
Project transfer. An owner of the original organization can run
`ccp db delete <sqlite-id>` and confirm permanent deletion. Use
`ccp db ls` to find the ID. A database still bound to an App rejects deletion.
The reservation counts toward the limit until its engine removes the live data.
During retries its status is `deleting`. Existing encrypted snapshots expire on
their normal retention schedule.

Page
through large tables with `LIMIT` and a `WHERE id > ?` cursor to stay under
the result limit.

## Errors [#errors]

A call that reaches the database and fails rejects with an `Error` whose
`code` is `sqlite_request_failed`. The same error covers invalid SQL, a
violated constraint, a result over the size limit, and a database that is
temporarily unreachable, so write statements whose outcome you can read from
the result:

```ts
const created = await env.DB.query(
  "INSERT INTO users (email) VALUES (?) ON CONFLICT (email) DO NOTHING RETURNING id",
  [email],
);
if (created.length === 0) {
  return Response.json({ error: "That email is already registered." }, { status: 409 });
}
```

A call that never reaches the database rejects with a plain `Error` that has a
message and no `code`:

| Message                        | What happened                                                    | What to do                                                   |
| ------------------------------ | ---------------------------------------------------------------- | ------------------------------------------------------------ |
| `SQLite database is not bound` | The App has no database, or the code is running under `ccp dev`. | Run `ccp db create --type sqlite`, and test on a deployment. |
| `SQLite request is too large`  | The SQL and parameters exceed the per-call limit.                | Split the work across calls.                                 |
| `Invalid SQLite batch size`    | `batch` received no statements or more than 64.                  | Send 1 to 64 statements.                                     |

`ccp db create --type sqlite` can fail with these errors:

| Error                                                         | What happened                                                                        | What to do                                                                                                   |
| ------------------------------------------------------------- | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
| `429` Your organization has reached its SQLite database limit | Your organization has reserved all of its databases. Existing bindings keep working. | Delete a detached database, reuse an existing App's database, or use [managed Postgres](/docs/ccp/database). |
| `503` The SQLite service is full, or SQLite is unavailable    | The service can't bind a database right now.                                         | Retry later.                                                                                                 |
