Database

Each app comes with its own SQL database, exposed as env.DB. It's SQLite at the edge, with the standard prepared-statement API. You define the schema; the platform reserves a small set of table names for its own managed features.

Querying with env.DB

Use prepared statements with bound parameters, never string interpolation:

// api/notes.js
export default {
  async fetch(request, env, ctx) {
    const user = await env.AUTH.getUser(request);
    if (!user) return new Response("Unauthorized", { status: 401 });

    // read many rows
    const { results } = await env.DB
      .prepare("SELECT id, body, created_at FROM notes WHERE user_id = ?")
      .bind(user.id)
      .all();

    return Response.json(results);
  },
};

The common methods:

  • .prepare(sql).bind(...args), build a parameterized statement.
  • .all(), all rows ({ results }).
  • .first(), the first row, or null.
  • .run(), execute a write (insert / update / delete).
  • env.DB.batch([...statements]), run several statements atomically.

Schema & migrations

Define and evolve your schema with SQL files under migrations/. Keep them ordered (a numeric prefix is the convention) so they apply deterministically:

-- migrations/0001_notes.sql
CREATE TABLE IF NOT EXISTS notes (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  user_id TEXT NOT NULL,
  body TEXT NOT NULL,
  created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_notes_user ON notes(user_id);

You can review what an app has defined with the list_migrations MCP tool. In practice you just ask your assistant for the schema you want and it writes the migration.

Numbering across branches. The prefix has to be unique across all branches, not just your own, count from what every branch has, not from your branch’s last file. If two branches both add 0042_*.sql, the merge is refused until one is renumbered. When several agents work in parallel, don’t guess: call manage_branch (action: reserve_migration) to claim the next free number atomically before you write the file, or read migrationCoordination.nextAvailable from manage_branch (action: list). See Working in parallel.

More than one database

One database handles a lot, but every query waits for the one before it, so a table that is written all the time (logs, events, imports) can slow down the rest of the app. An app can add more databases by name. Each one has its own capacity and its own 10 GB, and the same API as env.DB:

// api/track.js
const logs = env.DB.database("logs");
await logs
  .prepare("INSERT INTO events (kind, at) VALUES (?, ?)")
  .bind("signup", Date.now())
  .run();

A database is declared by its folder. Put its migrations in databases/<name>/migrations/, and the next deploy creates it:

-- databases/logs/migrations/0003_events.sql
CREATE TABLE events (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  kind TEXT NOT NULL,
  at INTEGER NOT NULL
);
  • Names use lowercase letters, digits and _, starting with a letter. main means env.DB itself.
  • The migration numbers are shared with migrations/: take the next free number for the whole app (reserve_migration works the same way).
  • Each database keeps its own databases/<name>/schema.sql up to date, like the root schema.sql.
  • There are no joins or transactions across databases, so keep tables that are read together in the same one. env.AUTH stays in env.DB.
  • Previews and branches get their own copy of each database, like they do of env.DB.
  • Your assistant can inspect and query one with database: "logs" on describe_app_db and query_app_db. In the dashboard each one is listed under the app's data.
  • An app can have up to 20 named databases. Usage is billed the same way as env.DB.
  • Moving the app's database to another region moves its named databases with it, checked the same way. Restoring to an earlier time is done one database at a time.
Reach for another database when describe_app_db says it's time to split, not before. A missing index is far more often the problem, and adding it is a one-line migration.

Moving existing tables to another database

An app that is already busy can move tables it has in env.DB into a named database, data and all. List them in databases/<name>/move_tables.json, in the same version as the code that now reads them with env.DB.database("<name>"):

// databases/logs/move_tables.json
["events", "event_tags"]

Your assistant can do this with the move_app_tables tool, which first checks that the move can go ahead. Each deploy of that version then does the move: the tables become read-only for a moment (reading still works), are copied with their indexes and triggers, and every row is checked. The new code goes live, and only then are the tables removed from env.DB. Deploy the branch first: the move runs in its preview, so you can test it before it runs on the live data.

  • Tables move together with whatever points at them: a foreign key, a trigger, a view or a full-text index can't point from one database into the other.
  • Big tables (tens of thousands of rows and up) move in the background when you deploy to production: they are copied and checked while the app keeps using them, and read-only only for the few seconds it takes to catch up with what changed meanwhile. Production is then deployed with the new version automatically. If anything goes wrong, the move is undone and the app keeps running as before, nothing lost.
  • Full-text tables (FTS5) can't be made read-only, so they are copied in those last seconds. Write to one in the same batch as a write to a normal table: the batch is then refused as a whole during that moment, and nothing written to the full-text table alone at the last second is lost.
  • A branch with a lot of data in its preview moves the same way, in the background, so it rehearses exactly what production will do.
  • A table that has been moved is remembered: if a table of the same name appears in env.DB again later, it is a new one and stays there (the deploy says so).
  • From then on, migrations for those tables go in databases/<name>/migrations/. The file can stay: tables already moved are skipped.

Reserved: the _cr_* namespace

Table names starting with _cr_ are owned by the platform, they back managed features like env.AUTH (_cr_users, _cr_sessions) and your app's own MCP OAuth server (_cr_oauth_*). They're created lazily on first use.

Don't create, write to, or migrate _cr_* tables yourself, name your own tables anything else. Use the env.AUTH methods to read or change user data.

Preview vs production data

A production (main) deploy uses the real app database. Branch and preview deploys run against a separate throwaway database, so work-in-progress can't corrupt live data, see Branches, PRs & merges.

By default a preview database starts empty, no production data is copied into it, so your customers' data is never duplicated into a sandbox. Seed whatever test rows you need. If you genuinely want realistic data in previews, an owner/admin can opt in with set_preview_data_mode ("light" for login/account data, "full" for app rows too).

What a query costs

Database use is billed by rows written, rows read and calls, plus the time the database is active (see usage prices). Rows read means every row a query scans, not just the rows it returns, including rows read by triggers and full-text search. A query on a column without an index reads the whole table each time, so an index on the columns you filter and sort by is the biggest saving.

Where your data lives

Each app keeps its database and files in one region: EU or USA. With EU, the database and the files are guaranteed to stay in the EU. With USA, the database is guaranteed to stay in the USA and the files are kept in North America. Your code always runs close to each visitor.

  • New apps use your workspace's region, set from where your workspace sits. Owners and admins can change it under Settings.
  • Pick another region for one app when you create it, or ask your assistant (region on create_app).
  • Move an existing app from its Settings (Data region). You can move its files and its database together or one at a time. Moving the files never stops the app: they are copied while it runs, then it switches over with a normal deploy. Moving the database makes the app read-only while it is copied (a few minutes, longer for a big database): people can still use it, but saving changes fails until the move is done, and it is offline for a few minutes of that. For a big app, move the files first and the database at a quiet time. Preview sandboxes are reset. Each move counts toward the 10 region changes allowed per app in 12 months; to change more often, contact us at hello@cloudrizz.com.
  • env.GEO, env.SEARCH and env.MEETING store their data in the EU (Frankfurt) for every app. AI features process data with their providers.