---
title: Database
description: Give an application a PostgreSQL database in each environment, set up when it is first needed, connected through runtime settings, and changed with migration files.
slug: /backend-packages/database
order: 2
visibility: public
redirects_from: []
---

# Database

Database gives your application its own PostgreSQL database in each environment, so you set up no database yourself. Each environment gets a database and its owner role, the database role that owns it. Turn Zero Cloud provisions the development database and its owner role when the [manifest](/cloud/concepts/glossary/#manifest) first declares the service, on every application. On an application with one environment, production, only [local runs](/cloud/concepts/glossary/#local-run) use the development database.

To start, add `{"kind": "database"}` to the manifest's `services` array and call `submit_manifest`, take the package with `turnzero library take --origin https://dev.turnzero.ai --entry database`, and open the pool from `APP_DATABASE_URL` in the process entry. A new service can start from one line instead, `turnzero scaffold --origin https://dev.turnzero.ai --template server-database` ([Build a database-backed service](/cloud/getting-started/build-a-database-backed-service/)).

Without a shell, start from the [server-database example files](/cloud/examples/server-database/) and follow the example's chat instructions. They explain how to declare library versions and deploy the files with `deploy_files`.

For testing without the CLI, see [Add a database, step 5 (Develop locally)](/cloud/guides/add-a-database/#5-develop-locally).
It covers offline tests, taking the package without an installed command, and testing through tools without a shell.

The package, `@turnzero/database`, is not on the npm registry. Take it with `turnzero library take --origin https://dev.turnzero.ai --entry database` (`turnzero.cmd` in Windows PowerShell). The CLI requires [authorizing the computer or supplying a minted token](/cloud/guides/use-the-library/); signing in to MCP does not authorize the CLI. Once installed, its test double runs in your tests without a Turn Zero credential or a database server. It is not an application preview mode; [Test your application locally](/cloud/guides/test-your-application-locally/) shows how to use it.

The production database is provisioned at the first deploy to production of an application with one environment, or at the first [promote](/cloud/concepts/glossary/#promote) of one with two, made while the manifest declares the database. A server's request pool reads `APP_DATABASE_URL`; work that needs one server session reads `APP_DATABASE_DIRECT_URL`. Its start code applies its migration files. A function environment receives one database connection setting, `APP_DATABASE_URL`. It uses pooler port 6432 on a shared database and direct port 5432 on a dedicated database. The platform applies its migrations before the version serves. [Add a database](/cloud/guides/add-a-database/) is the task, step by step.

A server application may declare a database. A shared database allows 10 client connections per process for both `shared-0.5gb` and `shared-1gb` applications. Where the platform supports only static serverless sites, it refuses a serverless database declaration with `serverless_unsupported` ([Serverless applications and servers](/cloud/concepts/serverless-applications-and-servers/)). An application’s shared database counts as one [monthly item](/cloud/concepts/glossary/#monthly-item) for both environments. The daily billing run includes the shared database even while the application’s servers sleep. Read its rate on the [pricing page](https://dev.turnzero.ai/pricing).

Database records and stored files share the 100 GB stored-data ceiling ([Current application limits](/cloud/guides/plan-and-usage/#current-application-limits)). Read current quantities with `read_plan_quotas`, passing `plan: "shared-0.5gb"` or `plan: "shared-1gb"`.

## Use it when

Use Database for structured records that need filtering, counting, joins, or transactional updates. Use Storage for file and blob contents.

Keep application preferences and other per-account records here as well. The Account client verifies identities and sessions and stores no such data.

Records you already hold in a JSON or CSV file reach the database as a migration file of their own. The server's start code, or the platform for a serverless application, applies it once in each database. [Carry existing records into the database](/cloud/guides/bring-an-existing-application/#3-carry-existing-records-into-the-database) shows the file and the script that writes it.

## What it provides

- **A database and role for each environment**, provisioned when the manifest declares `{"kind": "database"}`. The platform provisions the development database and its owner role on a development server at manifest submission. It provisions the production database and its owner role on a production server of the same [hosting cell](/cloud/concepts/glossary/#hosting-cell) at the first deploy to production or first promote, made while the manifest declares the kind.
- **`APP_DATABASE_URL`**, the environment's connection string. A pooled address gives each transaction one server connection. A direct address keeps one server session for a client connection. [A deployed app's settings](/cloud/concepts/the-settings-a-deployed-copy-receives/) explains which address your version receives. It carries `sslmode=verify-full`, which the `pg` driver reads as full certificate checking, so the pool needs no `ssl` option.
- **`APP_DATABASE_DIRECT_URL`**, for a server only, the direct connection string for [work that needs one server session](/cloud/guides/add-a-database/#work-that-needs-one-server-session).
- **`APP_DATABASE_CONNECTION_LIMIT`**, the pool's maximum, 10 client connections per process on a shared server. The deploy, the promote, and `restart_application` inject it, and the [provision command](/cloud/concepts/turnzero-command/#running-on-your-machine) writes it for a local run ([The connection limit](/cloud/guides/add-a-database/#the-connection-limit)).
- **The development connection facts.** A `submit_manifest` call returns them and `connection_limit`, the pool's maximum. It returns no credential to your tool ([Add a database](/cloud/guides/add-a-database/#5-develop-locally)).
- **Credential rotation.** The production credential is rotated only on request ([Add a database](/cloud/guides/add-a-database/#3-rotate-the-production-credential)). To replace a lost development credential, your AI coding agent runs `turnzero provision --origin https://dev.turnzero.ai --application <application id>` with nothing piped into the command. It makes any tool call the command prints, then runs the shell command the call returns.
- **A migration function (`applyMigrations`), a failover pool, and a startup function (`bootWalk`) that retries migrations when it cannot open a connection or loses one**, which [The client](#the-client) describes, with a migration [ledger](/cloud/concepts/glossary/#ledger) and an advisory lock.
- **Isolation by database role** on the shared server.
- **Removal with the environment.** Whether the application has one environment or two, `delete_environment` drops the development database and its owner role. The next manifest submission provisions both again for local runs. Deleting the application drops both databases and their owner roles.
- **A [test double](/cloud/concepts/glossary/#test-double)** at `@turnzero/database/testing`, a pool over an in-process PostgreSQL engine. [Test with the double](#test-with-the-double) shows it in use.

Each environment has its own database. A local run using the development environment file reaches the development database, from any address under the [developer network rule](/cloud/concepts/glossary/#developer-network-rule), and never production's.

To use standard PostgreSQL tools on your computer against production, follow [Connect to your database](/cloud/guides/connect-to-your-database/). Its approved connection gives your tool a temporary credential. The database package still uses the environment's own runtime settings.

## Availability

Version 0.16.2 is the package's current version, and this page describes it. Until the library's next publish, `read_library` can return an earlier version, the one you can take, so this page can describe a change that version lacks. The entry includes the `testing` subpath. The entry contains the compiled migration function, migration folder reader, and failover pool, the package's [product statement and detailed contract](/cloud/concepts/glossary/#product-statement-and-detailed-contract), and its integration guide. Your tool reads the integration guide with `read_library`, giving `entry` and `file: "features/database/integration.md"`.

A call to `apply_migration` or `restore_snapshot` returns 501 `not_yet_provisioned`, and a promote takes no snapshot. Automatic [database backups](/cloud/guides/add-a-database/#durability-and-backups) are kept for every application. An owner can [restore a dedicated production database](/cloud/guides/add-a-database/#restore-a-dedicated-database) to a chosen time. Restoring a shared database is a support request.

For a read-only look at an environment's data, your tool calls `query_database`, as [Read your data](/cloud/guides/add-a-database/#6-read-your-data) describes.

`set_database_size` requests a move of production's database to `database-dedicated-2gb`, `database-dedicated-4gb` or `database-dedicated-8gb`, or back to `database-shared`. Each dedicated size puts that database on a server of its own. Development stays shared. Production can move to a dedicated size in a server or serverless application. Each function worker should use at most one database connection. The move needs [browser approval](/cloud/concepts/what-happens-without-asking/#what-asks-first).

Production is unavailable from the freeze until its serving version restarts successfully or a revert restores production on the source server. Production deploys and promotes are refused with `database_move_in_flight` throughout the move, including server preparation. Repeat the refused act after the move ends.

Each day, a dedicated database costs that day’s share of the monthly rate for its size. When the new server is ready, Turn Zero adds that day’s charge for each dedicated size the move takes or leaves, before production freezes. Each size is charged once per application per UTC day. Charges already made stay on your account, including when the move fails.

A billed account can use a dedicated size only if the platform has opened it. Otherwise, `database_size_not_open` lists the dedicated sizes open to the account, or says none are open, and no pending action is created. The [`set_database_size` reference](/cloud/reference/actions/set-database-size/) gives the inputs, outcomes and refusals.

## PostgreSQL version and extensions

To check the PostgreSQL version of a Cloud database, run `SELECT version()` with [the read-only query action](/cloud/guides/add-a-database/#6-read-your-data). Choose the environment you want to check. Before a data move, check both the source and destination databases.

Use the source server's PostgreSQL major version or newer for `pg_dump`. For a custom archive, run `pg_restore --list` to check that your `pg_restore` can read it. The destination must support the objects in the dump. Rehearse the restore before moving production data.

For `psql`, match the server's major version or use a newer version when possible. An older `psql` can often run SQL. Some commands that start with a backslash may fail. Development connections need client tools version 16 or later for certificate verification. See [Connect to your database](/cloud/guides/connect-to-your-database/).

Your application's role can create objects in its database. Use `CREATE EXTENSION` in a migration to create a supported extension. Your application's role owns the extension it creates. Use `CREATE EXTENSION IF NOT EXISTS` if the migration may run more than once.

The supported extensions are `pgcrypto`, `uuid-ossp`, `citext`, `pg_trgm`, `hstore`, `btree_gin`, `btree_gist`, `ltree`, `fuzzystrmatch`, `tablefunc`, and `unaccent`. The same list applies in development and production, on shared and dedicated databases.

The database refuses any other extension. For a serverless migration, this refusal fails the deploy at the `migrations` step with `migration_failed`. The failure detail names the migration file and gives PostgreSQL error `0A000`.

## Related feature packages

[Storage](/cloud/backend-packages/storage/) stores files and blobs. [Account](/cloud/backend-packages/account/) verifies the identities your application records belong to.

## The client

If your deploy includes this package, use version 0.14.0 or later. The platform refuses older versions with `database_package_outdated`. The package works over the `pg` driver's pool, which your application installs. The package is optional: the platform needs only the manifest's declaration and `APP_DATABASE_URL`, and [Without the Database package](/cloud/guides/add-a-database/#without-the-database-package) shows a server on `pg` alone. [Connect to it](/cloud/guides/add-a-database/#2-connect-to-it) shows the three functions together in one data module, which a test runs.

### The migration function

The function `applyMigrations(query, files)` applies every `.sql` file the ledger table `schema_migrations` does not list, in name order, and returns the names it applied. The argument `query` is a function tied to one database connection, `(text, values) => client.query(text, values)`. The argument `files` lists the file names and reads one by name. The function `migrationsFrom('migrations')`, from `@turnzero/database`, gives one over your `migrations` folder, and the testing subpath exports the same function. Your application calls `applyMigrations` before it serves requests.

`applyMigrations` creates and updates `schema_migrations` in your application's database. Turn Zero Cloud provisions the database and credentials. For a serverless application, it also runs this package's migration function at deploy, promote and rollback, using the same ledger and lock. [Serverless migrations](/cloud/guides/add-a-database/#serverless-migrations) describes the files, limits and failure recovery. A server with another migration tool follows that tool's schema and history rules instead.

- It takes an advisory lock inside each transaction, released at commit or rollback. Each file has its own transaction, which reads its ledger row again after taking the lock and skips a file another copy applied.
- A file may contain several SQL statements and dollar-quoted (`$$`) function bodies because the migration function and the test double run it whole as one query without values.
- It ignores names that do not end in `.sql`, so a folder listing can be passed as it is.
- It strips one byte-order mark (BOM) from the start of each file before it runs the file. A BOM anywhere else in the file is passed to the server as written.
- If a file fails, the earlier files stay applied, and the function throws: your application must stop before serving.
- It records a hash of each file's content, and throws `MigrationEditedError`, naming the file, before any file runs where a recorded file was edited. Add a new file instead, or clear the development database where only it ran the file.
- It also throws if a commit fails. The database server releases the transaction's lock. `applyMigrations` issues no unlock statement.
- When it throws, release the connection it ran on with the error, as in `client.release(error)`. The `pg` pool then discards that connection instead of reusing it.

The `schema_migrations` columns are `name` (`text`, the file name and primary key), `applied` (`timestamptz`, the row's recording time), and `sha256` (`text`, the file's content hash in hexadecimal).

### The failover pool

The platform's application database servers have no standby. A server restarts in place for maintenance or after a machine failure. During a restart, the server ends every open database session and accepts no connection until it is ready. In Node.js, an ended session your code does not listen for stops the process. If the server's zone fails, its databases stay unavailable until the zone returns.

The function `createFailoverPool({ connect, max, windowMs, connectTimeoutMs, onConnectionLoss })` returns a pool with `query`, `connect`, and `end`, and the driver's pool as `driverPool`. It calls your factory, which builds the `pg` pool, and listens for those ended sessions, so the process keeps serving.

| Option | Default | Meaning |
| --- | --- | --- |
| `connect` | Required | Your factory, `(settings) => new pg.Pool({ connectionString, ...settings })`, called once with `max` and `connectionTimeoutMillis`. |
| `max` | Required | The pool's maximum: the number your process entry reads from `APP_DATABASE_CONNECTION_LIMIT`. |
| `windowMs` | 120,000 | How long `bootWalk` retries a lost connection at start, in milliseconds. |
| `connectTimeoutMs` | 5,000 | The longest one connection attempt waits. |
| `onConnectionLoss` | None | A function called for each session the server or the network ended. |

The pool passes `connectTimeoutMs` to the database driver for each connection attempt. The default is five seconds. Your process entry still reads `APP_DATABASE_CONNECTION_LIMIT` and passes it to the pool as `max`.

### The startup walk

The function `bootWalk(pool, files, { onRetry })` runs `applyMigrations` over one connection from the pool and returns the names it applied. It retries only when it loses a database connection, whether while opening it or during the migration. This does not mark the file as failed. It waits one second between attempts and starts no attempt after `windowMs` expires. The default window is 120 seconds. If the window ends before it can retry, it fails with `failover_window_ended`. It calls `onRetry(error, attempt)` before each retry wait.

Run `bootWalk` before the server listens, so a failed migration ends the process before it serves. Once it listens, answer your health path with 200 only while one short database read succeeds, and with 503 while it fails ([The deploy health check](/cloud/concepts/the-deploy-health-check/)).

### Failures

- The startup walk, `bootWalk`, rejects with a `FailoverPoolError` whose `code` is `failover_window_ended` and whose `cause` is the last lost connection, once the window has passed.
- `applyMigrations` rejects with the error from a failed file or commit. `bootWalk` retries a lost connection as described above. Any other error stops startup immediately and is passed to the caller unchanged.
- For a recorded file that was edited, they reject at once with a `MigrationEditedError` whose `code` is `migration_edited`, and run nothing. The process entry refuses to serve, as for a failed file.
- A query on the pool rejects with the driver's own error. The function `isConnectionLoss(error)` says whether the error is a lost connection.

## Test with the double

The test double, `createDatabaseDouble({ engine, files })` from `@turnzero/database/testing`, is a pool with the `pg.Pool` shape over a PGlite engine your test constructs, with your migration files applied at construction. PGlite is a PostgreSQL build that runs inside the Node.js process, so the tests run offline with no development database. The engine package is `@electric-sql/pglite`, a development dependency at version 0.5.8, the version the double is tested against. The function `migrationsFrom('migrations')` reads a folder of migration files.

The package's library entry includes the double as `lib/testing.js`, which imports `lib/migrations.js` and `lib/files.js`. Your committed package copy gives every clone and CI run the same double, which runs without a Turn Zero credential. A signed-in AI coding agent with no CLI token can read these files through `read_library`. Set `entry` to `database` and `file` to each path: `features/database/lib/testing.js`, `features/database/lib/migrations.js`, and `features/database/lib/files.js` ([Use the feature package library](/cloud/guides/use-the-library/)).

The pool's `query` takes a text and its values, or a query object such as `{ text, values }`, and returns the same rows either way. An object that sets `rowMode: 'array'`, `types`, or `binary`, or passes a callback, is refused with a code naming the option, such as `query_row_mode_unsupported`, because the double cannot return those results. A test runs this sample over the double.

```js
import assert from 'node:assert/strict';
import { PGlite } from '@electric-sql/pglite';
import { applyMigrations } from '@turnzero/database';
import { createDatabaseDouble } from '@turnzero/database/testing';

// One migration file, given in memory; migrationsFrom('migrations') reads the folder instead.
const files = { list: () => ['0001_notes.sql'], read: () => 'CREATE TABLE notes (id serial PRIMARY KEY, title text NOT NULL);' };
const database = await createDatabaseDouble({ engine: new PGlite(), files });
assert.deepEqual(database.applied, ['0001_notes.sql']);

await database.pool.query('INSERT INTO notes (title) VALUES ($1)', ['first']);
const { rows } = await database.pool.query('SELECT title FROM notes');
assert.deepEqual(rows, [{ title: 'first' }]);
// The ledger already lists the file, so the migration function applies nothing more.
const client = await database.pool.connect();
assert.deepEqual(await applyMigrations((text, values) => client.query(text, values), files), []);
client.release();
await database.close();
```

### Use the double in your tests

Install `@electric-sql/pglite@0.5.8` as a development dependency and import the double from `@turnzero/database/testing`. To use the migrations from your application, import `migrationsFrom` from that same entry and pass `files: migrationsFrom('migrations')`. Leave out `files` to start with no migrations.

Pass `double.pool` to the same data layer that takes your application's pool. Check its rows and errors as you would with PostgreSQL. The double runs the migration files at construction and gives their names in `applied`. If a migration fails, construction rejects with the engine's error.

Call `await double.reset()` between cases that share an engine. It empties public tables, restarts identity counters and keeps the migration ledger. Seed each test again after a reset. Call `await double.close()` after the tests to end the engine.

Use a checked-out client's `query` until you release it, and put `client.release()` in a `finally` block. The double has one session. A second checkout or a `pool.query` while you hold a client waits for its release. It refuses with `session_held` after `waitMs` (5,000 milliseconds by default).

`double.statements` records SQL issued through the pool or its clients, including migrations and any bound values. The double tests queries and schema constraints offline. Use a hosted test for managed-server behavior such as TLS, failover or locking across multiple sessions.

[Test your application locally](/cloud/guides/test-your-application-locally/) shows how to write the data layer as a factory over a pool and lists the double's refusals. The database library entry's `features/database/integration.md` documents every option, including the shape of each recorded statement.
