Platform

SQLite

Give a Serverless App its own SQLite database and query it from your handler with env.DB.

View as Markdown

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 when you need more than 64 MB, a database shared by several Apps, or access from outside the App.

Quickstart

From a linked App directory:

ccp db create --type sqlite

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

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 });
}
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.

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

What you might expectHow SQLite works
A connection string in .envThere isn't one. The binding belongs to the App, and env.DB is available in every deployment of it.
A database per deploymentPreview 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 backupsThese manage Postgres. Query SQLite from your handler.
A local database in ccp devenv.DB works only in a deployed App. Under ccp dev, calls reject. Test database code on a preview deployment.

Query from a Handler

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

MethodReturnsUse it for
env.DB.query(sql, params?)Promise<Row[]>One statement.
env.DB.batch(statements)Promise<Row[][]>, one array of rows per statementSeveral 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:

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

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

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

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

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

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 tables from your App, in a statement that is safe to run again:

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.

Limits

LimitValue
Database size64 MB
Databases per App1
Databases per organization8
Statements per batch64
SQL and parameters per call256 KB
Result size per call1 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

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:

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:

MessageWhat happenedWhat to do
SQLite database is not boundThe 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 largeThe SQL and parameters exceed the per-call limit.Split the work across calls.
Invalid SQLite batch sizebatch received no statements or more than 64.Send 1 to 64 statements.

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

ErrorWhat happenedWhat to do
429 Your organization has reached its SQLite database limitYour 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.
503 The SQLite service is full, or SQLite is unavailableThe service can't bind a database right now.Retry later.

On this page