Skip to content
runlot

Database

A PostgreSQL database for your app, created when your app uses one. Use it from your worker as env.db — no connection string, no secrets.

A database is created when your app uses one. Your worker reaches it as env.db. The database runs on the same machine as your app and is reached through a binding, so there is no connection string to store as a secret.

const rows = await env.db.exec("select id, name from users where id = $1", [1]);

When a database is created

A project gets its database the first time one of these happens.

  • Your code uses one. runlot deploy looks at the build. If it imports @runlot/pg, pg or an ORM on top of it, or @runlot/auth, has a migrations/ folder, or uses env.db in your own source files, the deploy creates the database before the new version goes live.
  • You ask for one. Run runlot pg on, or create it on the Database page of the dashboard.
  • A feature needs one. Turning auth on, or declaring queues in runlot.json, creates it, because both keep their data in the database.
  • Your app calls env.db anyway. If the build gave no sign that it uses a database, the first call creates it. Calls made while it is being created reject with DatabaseStarting. Retry them after a few seconds.

A new database starts empty. A project that never uses a database does not get one.

The database field in runlot.json

runlot deploy decides from the build. To decide yourself, set database in runlot.json. A value you set always wins over the build.

{
  "name": "my-app",
  "main": "src/index.ts",
  "database": false
}
  • true — the deploy creates the database, whatever the build imports.
  • false — no database is created automatically. A call to env.db rejects with DatabaseNotEnabled, and a deploy that declares queues is refused. It does not delete a database the project already has; runlot pg delete does that. runlot pg on still creates one.
  • Leave it out to let the build decide.

A database you deleted with runlot pg delete is not created again by a deploy. Run runlot pg on to create a new one.

Errors from env.db

ErrorWhenWhat to do
DatabaseStarting"The database is being created for this project — retry in a few seconds." It happens once, on the first call of a project whose build gave no sign that it uses a database.Retry the call after a few seconds.
DatabaseNotEnabled"This project has no database. Remove "database": false from runlot.json, or turn it on with runlot pg on."Do one of the two, then deploy again.

One database per project

There is no database name to choose, so the binding is always env.db. If you need more than one database, split the work into separate projects.

Pages in this section

Getting started

  • env.db — the four APIs you use from a worker
  • Your first query — from creating a table to reading rows back
  • @runlot/pg — a Pool that behaves like node-postgres

Operating

Reference

On this page