Add a database #
On this page
Add PostgreSQL to an existing app, connect your code, and manage changes to its tables. Read this page when your app needs to save records, or when you need to test or troubleshoot its database connection.
Prompt:
Add a database to this app.
Also works:
- "We need somewhere to keep the orders and the customers."
Add PostgreSQL to an existing application by declaring {"kind": "database"} in its manifest and connecting through APP_DATABASE_URL. For a new service, start with Build a database-backed service. See Database environment variables for what the deployed copy receives.
Check Before your AI starts for the sign-in, application ID and manifest. Use this checklist.
- Declare the database. Add
{"kind": "database"}toservicesand submit the whole manifest withtzcloud_submit_manifest. - Connect your code through
APP_DATABASE_URL. On a server, set the pool limit fromAPP_DATABASE_CONNECTION_LIMIT. In a function, use at most one connection per worker. - Keep schema changes as ordered SQL files. Your server runs them before it listens. For serverless, the platform runs them before the deployed version serves.
- Test locally. The package’s test double needs no database. For a local run, use your own PostgreSQL or provision the development database’s credentials. With no shell, check a development deploy instead if development is enabled.
- Check your data with a read-only query. Name the environment you want to check.
Rotate the production credential only when requested. For other work, see Database sizes, Durability and backups, or Restore a dedicated database. Expected result and Refusals explain successful responses and remedies.
Your AI assistant can use the Database package for its failover pool, migrations, and test double. Taking it requires this computer's token, a minted token, or a signed-in MCP connection. Develop locally explains the command route. An assistant without a shell can read the package through its signed-in connection with tzcloud_read_library.
To use the pg driver alone, follow Without the Database package, which gives a whole server with no scaffold or package to take. For an existing CommonJS application, use CommonJS and Express and the CommonJS migration helper. This avoids taking a Turn Zero package; declaring the database and deploying the application still require Turn Zero credentials.
For testing without the CLI, see Add a database, step 5 (Develop locally). It covers offline tests, taking the package without an installed command, and testing through tools without a shell.
Turn Zero Cloud provisions the database and credentials. You keep the schema changes as migration files. A server applies them at start; the platform applies them before a serverless version serves. For a serverless app, follow Declare it, the function setting in Connect to it, and Serverless migrations. Skip the server start-code examples. Some server examples use the Database package and its schema_migrations ledger. Others use pg alone. A server with another migration tool can keep that tool and its history.
For documents, uploaded images, and other files, use Storage. The Database and Storage pages explain when to use each.
Durability and backups explains what survives and how long backups are kept. Start after idle and response time explains the wait when a stopped environment starts again.
If you want to search existing records. Put the search behind an app route. For private records, use the signed-in user's ID to apply the same access rule you use when listing records. Keep the SQL statement fixed and bind the search text as a parameter. Limit the number of rows the query returns. Try two users who search for the same word and confirm each sees only their allowed rows. See row-level security.
What your AI does #
- Reads the
add-serviceskill (read_context, idskill:add-service) and follows it: it declares the database in the manifest, submits it, and follows the steps below. - For an ESM server, prefers the Database package. Copies it into the project's library folder,
system/, as Use the feature package library describes, and addspgbeside it underdependenciesinpackage.json. For a server, the deploy's image build installs those withnpm install --omit=devand then runsnpm start(What the deploy zip holds). If the library is unavailable, follow Without the Database package for a server onpgalone. The npm registry carries no@turnzeropackage, sonpm view @turnzero/databasefinds none: the package reaches a project from the library alone, by thelibrary takecommand. - For an ESM server using the package, writes the data module, the migration files, and the start code as step 2 (Connect to it) shows. Runs the application's tests over the package's test double. The package's migration function,
applyMigrations, applies the files, so the project needs no migration runner of its own. - Rotates the production credential or clears the development database only when you ask, and gives you the approval link the clear needs.
- Asks for no separate browser approval for
tzcloud_submit_manifest,tzcloud_store_secretwithreplace: true,tzcloud_set_app_size,tzcloud_restart_application,tzcloud_deploy, ortzcloud_promote. Your AI still follows the work you authorized.
Before your AI starts #
For the AI assistant: Check the following before starting.
- A connected, signed-in AI assistant (Connect your AI assistant).
- The application's identifier from
tzcloud_list_applications, and its manifest (Author the manifest). - For a server or local run, set each process's pool maximum from
APP_DATABASE_CONNECTION_LIMIT. The usual limit for a shared database is 10 client connections per process. A dedicated database uses its size's limit. Readconnection_limitintzcloud_read_status. For a function, follow the function setting in Connect to it.
Steps #
1. Declare it #
Add {"kind": "database"} to the manifest's services array and call tzcloud_submit_manifest with the whole manifest. Declare the database shows that whole manifest, every required field included. For each environment, the platform creates one PostgreSQL database and one database role, the database user your code signs in as:
- The development database, on a development server, is created when you submit. Your local runs and a deployed development environment use it.
- The production database, on a production server, is created at the first deploy on an application with one environment, or the first promote on one with two. The manifest must still declare the database then.
Every application with a database gets a development database, even one with a single environment, so local test data never lands in production's. It makes no difference whether you call tzcloud_create_environment before or after this submission: the submission creates the development database and its owner role either way.
The response gives the development database's connection details as development_database and production's pool maximum as connection_limit. The response's note gives development's pool maximum. For this local setup, turnzero provision --origin https://dev.turnzero.ai writes the development credentials to a .env file; step 5 (Develop locally) says how your AI coding agent runs it.
Only the platform holds the standing production database credential. The first deploy or promote that reaches production creates it. For a server, the platform composes production's APP_DATABASE_URL and APP_DATABASE_DIRECT_URL from it. For a function, it composes APP_DATABASE_URL alone. No setting's value is shown to you. Declaring the service again does not reset a database that already exists.
The shared database is charged by the day.
One monthly rate covers production and development together. The daily billing run charges a day’s share when it finds the shared database held, even while the server sleeps. The shared charge stops at the first run after production moves to a dedicated size or the application is deleted. Charges already made stay on the account. Read the rate on the pricing page or with read_rate_card.
2. Connect to it #
A function environment receives APP_DATABASE_URL alone. It connects through pooler port 6432 on a shared database and direct port 5432 on a dedicated database. The connection checks the server’s certificate against its name. Use at most one connection per function worker.
The platform opens its own direct connection for serverless migrations. The two-setting examples and direct-session advice below are for a server or a local run.
Use the port in APP_DATABASE_URL, the PostgreSQL connection string. Port 6432 uses a pooler that assigns a connection per transaction. Port 5432 connects directly. APP_DATABASE_DIRECT_URL names the server's direct port, 5432, for work that needs one server session. Both carry sslmode=verify-full, which the pg driver reads as full certificate checking, so neither needs an ssl option.
For a server application, the unlimited plan and a dedicated database server use the direct address at every act. Other servers select the pooled address on deploy. A promote, rollback, restart or platform redeploy preserves that server version's recorded address, defaulting to direct where none was recorded.
For libpq in a server image, set PGSSLROOTCERT to the CA bundle and keep sslmode=verify-full.
For a local run, turnzero provision --origin https://dev.turnzero.ai writes the pooled address as APP_DATABASE_URL and the direct address as APP_DATABASE_DIRECT_URL in its settings file. To run psql, pg_dump, or pg_restore against development, use turnzero db connect --environment development with that file. Connect to your database shows the commands.
Take the host name only from these settings, because the server's name can change at a promote or when the platform moves the database. If the platform cannot read the stored credential, the deploy, promote or rollback fails with database_credential_unreadable instead of starting without the settings.
A deploy that carries the Database package needs version 0.14.0 or later; an older copy is refused database_package_outdated.
The platform needs only the declaration and the setting, and any PostgreSQL driver works. The sample below uses the Database package for three things: its failover pool, its code that applies the migrations at start, and its test double. It is the data module that Build a database-backed service writes, and it works unchanged in an application you already have. A test checks that each of its three files matches that service's file, and runs the module over the package's test double. For a server on the pg driver alone, see Without the Database package.
src/db.mjs opens the pool from the two settings, runs the migrations, and holds the queries:
// src/db.mjs
import { fileURLToPath } from 'node:url';
import pg from 'pg';
import { bootWalk, createFailoverPool, migrationsFrom } from '@turnzero/database';
const MIGRATIONS = fileURLToPath(new URL('../migrations/', import.meta.url));
const HEALTH_READ_MS = 2_000;
// The live pool, which only the process entry opens: the package's failover
// pool over a pg pool. APP_DATABASE_CONNECTION_LIMIT sets its maximum.
// The platform supplies it; the turnzero command's provision writes it for
// a local run. The pool uses one connection where the setting is absent.
export function openLivePool() {
const url = process.env.APP_DATABASE_URL;
if (!url) throw new Error('APP_DATABASE_URL is not set');
const limit = process.env.APP_DATABASE_CONNECTION_LIMIT ?? '';
const max = /^[1-9][0-9]*$/.test(limit) ? Number(limit) : 1;
return createFailoverPool({
// settings is { max, connectionTimeoutMillis }: the maximum and the five-second connect limit.
connect: (settings) => new pg.Pool({ connectionString: url, ...settings }),
max,
onConnectionLoss: (error) => console.warn('database session ended:', error.message),
});
}
// The migrations through the package's boot walk: a lost connection retried
// every second for up to 120 seconds, and any other failure ends the start.
export function migrate(pool) {
return bootWalk(pool, migrationsFrom(MIGRATIONS), {
onRetry: (error, attempt) => {
if (attempt === 1) console.warn('database unreachable at start; retrying:', error.message);
},
});
}
// The data layer over any pool with the pg.Pool shape: the live one, or a test double's.
export function createDataLayer(pool) {
return {
// One read over the connection, bounded so a probe never waits on a lost database.
async reachable() {
let timer;
const late = new Promise((resolve) => { timer = setTimeout(resolve, HEALTH_READ_MS, 'late'); });
try {
return (await Promise.race([pool.query('SELECT 1'), late])) !== 'late';
} catch {
return false;
} finally {
clearTimeout(timer);
}
},
async addNote(title) {
const { rows } = await pool.query('INSERT INTO "notes" (title) VALUES ($1) RETURNING id, title', [title]);
return rows[0];
},
async listNotes() {
const { rows } = await pool.query('SELECT id, title FROM "notes" ORDER BY id');
return rows;
},
};
}
migrations/0001_notes.sql creates the table the queries use:
-- migrations/0001_notes.sql
CREATE TABLE "notes" (
id bigserial PRIMARY KEY,
title text NOT NULL CHECK (title <> '')
);
src/main.mjs, the start code, opens the pool, runs the migrations, and only then listens:
// src/main.mjs, the process entry the start script runs
import { createDataLayer, migrate, openLivePool } from './db.mjs';
import { createAppServer } from './server.mjs';
const pool = openLivePool();
const applied = await migrate(pool);
console.log(applied.length > 0 ? `migrations applied at this start: ${applied.join(', ')}` : 'migrations: none pending at this start');
const port = Number(process.env.PORT ?? 8080);
createAppServer(createDataLayer(pool)).listen(port, () => console.log(`listening on ${port}`));
Replace the notes table and its two queries with your own, and createAppServer with your application's server. Its health route calls reachable() and returns 200 when it is true and 503 otherwise, as Serve the health path over the connection shows. Keep the split the sample makes. Only the start code opens the live pool, and no module opens one when it is imported. Your tests hand the same data layer the test double's pool, as Test your application locally shows.
Each role can reach its own database and no other. The platform runs, patches, and backs up the database server. The development server's public endpoint accepts a connection from any address under the platform's developer network rule. The connection is encrypted with TLS, and the credential controls access, so a local run reaches the development database from any machine.
Production database servers require TLS. Applications reach shared servers through private endpoints. Shared servers admit no customer addresses. New dedicated servers run in a subnet reserved for PostgreSQL servers and have no public endpoint. For approved access from your computer, use Connect to your database.
Claim a slot without overwriting it #
For a fixed appointment or reservation slot, give that slot one canonical key. Derive it from the resource and its fixed start time, using the same format for every request. Two keys for the same slot would allow two claims. This pattern claims one key; it does not detect overlapping time intervals.
Add this table through a new ordered migration, keeping any migrations already applied unchanged:
CREATE TABLE slot_claims (
slot_key text PRIMARY KEY,
claimed_by text NOT NULL
);
Put the following operation in your backend's data layer, using its existing pool. Validate the requested slot and derive claimantId from the verified user session, never a user identifier supplied in the body.
// src/slot-claims.mjs
export async function claimSlot(pool, slotKey, claimantId) {
const { rows } = await pool.query(
`INSERT INTO slot_claims (slot_key, claimed_by)
VALUES ($1, $2)
ON CONFLICT (slot_key) DO NOTHING
RETURNING slot_key, claimed_by`,
[slotKey, claimantId],
);
return rows[0] ?? null;
}
A returned row means this call claimed the slot. null means it inserted nothing: the key already exists. The conflict clause leaves the earlier claim unchanged, including when another user calls. Keep other write paths from updating an existing claim if your application promises never to overwrite one.
A retry after a lost answer can return null even when the first call succeeded. To confirm that person's claim, read it under their verified identity instead of replacing it. This prevents a second stored claim; it does not make payment, email or another side effect run exactly once.
Test the first claim, a repeat, competing claimants and a different slot. Confirm that the first stored claimant stays unchanged. Build a webhook receiver with a database uses the same unique-key conflict clause to save each delivery once.
The connection limit #
Each process is bounded by its size's database-connection-limit. tzcloud_submit_manifest returns the limit as connection_limit, and tzcloud_read_status and tzcloud_read_plan_quotas return it too. A deployed server receives it as APP_DATABASE_CONNECTION_LIMIT; the provision command writes the setting for a local run.
Set your pool's maximum from that setting, never higher. The sample's openLivePool does this and uses one connection if the setting is absent. During a deploy or promote, both copies run from the new copy's start through its health check and for about 15 seconds after the switch. Through the pooled address, both copies share the pooler's server connections for their role and database.
On a shared server, the pooler opens up to 5 server connections for each role and database. Each runs one transaction at a time. Every process and running copy using that role and database shares those connections. This limit is the same in development and production for every app size. Dedicated databases use the direct address.
The database role allows up to twice connection_limit in server connections. For example, a per-process limit of 10 allows 20 server connections for the role. These include the pooler's server connections and every direct connection: APP_DATABASE_DIRECT_URL, tzcloud_query_database, and a version whose APP_DATABASE_URL still names the direct port. The role's bound counts server connections, rather than each client's connection to the pooler.
By default, PostgreSQL cancels a statement after 30 seconds and ends a session after 60 seconds idle in an open transaction. For longer work such as a bulk load, use SET LOCAL in each transaction that needs a longer timeout on either address. To change a timeout for the whole session, use SET on APP_DATABASE_DIRECT_URL.
The server limits temporary files to 256 MB per session, and your application's role cannot change that limit. query_database keeps its own 10-second statement limit, and the platform's overall time limit still applies to serverless migrations.
Through the pooled address, a transaction that finds no server connection free waits up to 15 seconds, then fails. A pool larger than connection_limit therefore does not fail at once with too many connections for role; transactions wait instead. Keep queries short and return connections promptly, so the health path's read does not wait behind long work.
Through the direct address, PostgreSQL refuses a connection over the role's limit with too many connections for role. An oversized old pool can leave the new copy without a connection during a promote, restart or platform redeploy, so its health check fails. Read the failed record's gate result or tzcloud_read_logs with source: "container". Set the pool's maximum from APP_DATABASE_CONNECTION_LIMIT, then deploy again.
A running copy keeps the setting it started with. After a change to the connection limit, the role's limit changes at once; each environment's next deploy, promote or tzcloud_restart_application supplies the new setting.
A restart starts its new copy beside the old one; the old copy leaves only after the new one passes its health check. If an old pool holds connections past the health-check window, the restart can fail and leave the old copy serving. Retry once its idle connections close.
A running database environment not re-created by a size change reads its connection setting only at its next restart, deploy or promote. Restart such an environment after the size change; production re-created by the change needs no further restart. The response to the size change does not list which environments need a restart. An environment with no running copy takes the setting at its first deploy or promote.
Work that needs one server session #
For a shared database, limit your APP_DATABASE_DIRECT_URL pool to 4 connections, or 3 beside your own direct migration client, leaving room for both deployed copies and a query session.
Treat this as a budget for the whole running copy. Count every direct connection from the main process and any child process, including a listener's connection outside its pool.
The pooled address cannot preserve a server session between transactions. Use APP_DATABASE_DIRECT_URL for session advisory locks, LISTEN, session-level SET, temporary tables that must survive a transaction, or cursors held open after one. Ordinary queries and transactions use APP_DATABASE_URL. Database package 0.14.0 and later take their migration locks inside transactions and work through that address.
If your migration holds a lock across transactions, use APP_DATABASE_DIRECT_URL, or take and release the lock within each transaction. A local run with the provisioned APP_DATABASE_URL exercises the pooler. Use those settings to test migrations that take and release the lock within each transaction.
Statements prepared by name through the protocol work through APP_DATABASE_URL. In pg, a query prepares by name only when its config includes name; the Database package passes that config through. The SQL statement PREPARE belongs on APP_DATABASE_DIRECT_URL: a later EXECUTE through the pooled address may reach another server connection.
A schema change that alters a named statement's result shape can fail with 0A000, "cached plan must not change result type". One example is SELECT * over a table that gains a column. The old plan keeps failing until the pooler replaces its server connection: about 30 seconds on an idle pool or an hour on a busy one. Other statements keep working.
Restarting or deploying again with the same statement text does not end the failure if the new copy reconnects while the pooled server connection is still live. Change the text, for example by listing the columns, send the statement unnamed, or use APP_DATABASE_DIRECT_URL within the connection bound above.
Keep each signed-in user’s rows private #
Use PostgreSQL row-level security to let each signed-in user read and change only their own rows. Your application connects through its own database role. That role owns the tables its migrations create. Its PostgreSQL attributes include NOSUPERUSER and the default NOBYPASSRLS. PostgreSQL normally skips row policies for a table’s owner, so enable and force row-level security on each table that needs it.
Add the table and its policy in a migration. This example uses a text column for the user ID. The policy checks both the rows a query can see and the rows a write can save.
CREATE TABLE private_notes (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id text NOT NULL,
body text NOT NULL
);
ALTER TABLE private_notes ENABLE ROW LEVEL SECURITY;
ALTER TABLE private_notes FORCE ROW LEVEL SECURITY;
CREATE POLICY private_notes_owner ON private_notes
USING (user_id = NULLIF(current_setting('app.user_id', true), ''))
WITH CHECK (user_id = NULLIF(current_setting('app.user_id', true), ''));
In your function or server, verify the user’s session. Take the ID from the verified session. Open a database transaction and run both statements below on the same transaction client. Commit when they succeed or roll back if a query fails.
await tx.query("SELECT set_config('app.user_id', $1, true)", [verifiedUserId]);
const { rows } = await tx.query('SELECT id, body FROM private_notes ORDER BY id');
The third argument to set_config keeps the setting inside that transaction. Set it again for each transaction. The pooled APP_DATABASE_URL can assign a server connection to a different request after the transaction ends, so use a transaction-local setting.
With this policy, a transaction without a user ID sees no rows. That includes a normal read with tzcloud_query_database. Migrations connect as the same role. With row-level security forced, data updates and deletes in a migration can affect only the rows its policy allows.
Keep Supabase row policies #
On Supabase, auth.uid() returns the signed-in user's UUID. After the move, your backend verifies the user's session and supplies the UUID for each database transaction. You can keep a policy that compares an owner UUID to auth.uid() if it has no other Supabase dependencies.
Add this function to a migration.
CREATE SCHEMA IF NOT EXISTS auth; CREATE OR REPLACE FUNCTION auth.uid() RETURNS uuid LANGUAGE sql STABLE AS $$ SELECT NULLIF(current_setting('app.user_id', true), '')::uuid $$;Enable and force row-level security on each protected table. Your application's database role owns its tables. Forcing row-level security makes PostgreSQL apply the policies to queries run by that owner. Run these statements with the name of each table whose imported policy uses
auth.uid().ALTER TABLE private_notes ENABLE ROW LEVEL SECURITY; ALTER TABLE private_notes FORCE ROW LEVEL SECURITY;Verify the session in your backend. When the restored rows still use Supabase IDs, look up the linked Supabase UUID from the verified Turn Zero user. Use that old UUID as
userId. Set it at the start of the transaction and run every protected query on the same transaction client.await tx.query("SELECT set_config('app.user_id', $1, true)", [userId]);
Commit when the work succeeds and roll back if a query fails. The setting lasts for one transaction. With no ID set, auth.uid() returns NULL, so a policy that requires equality with the owner UUID matches no rows.
Rehearse in development with two signed-in users who have different imported rows. Check that each sees their own rows and cannot write a row as the other user. Open a new transaction without setting the ID and check that the owner policy returns no rows.
Driver options through the pooled address #
The pooled address refuses these pg client or pool options at sign-in with 08P01: statement_timeout, lock_timeout, idle_in_transaction_session_timeout, and options carrying one of them or search_path. The server's words are unsupported startup parameter: statement_timeout, unsupported startup parameter: lock_timeout, or unsupported startup parameter: idle_in_transaction_session_timeout. For options carrying -c statement_timeout=..., they are unsupported startup parameter in options: statement_timeout. With -c search_path=pg_catalog, they are unsupported startup parameter in options: search_path.
Set the timeouts or search path inside each transaction with SET LOCAL. Alternatively, use APP_DATABASE_DIRECT_URL. For a shared database, keep that pool within the 4-connection bound, or 3 beside a direct migration client. query_timeout is different: it is the driver's timer in the client process, is sent nowhere, and works on both addresses. The Database package's own pool sets none of the four refused options.
Restarts and zone failures #
Each application database server runs in one availability zone with no standby, in production and development alike. A server restarts in place for maintenance, on Sunday between 14:00 and 15:00 UTC, or after a machine failure. A restart ends every open session, and the database accepts no new connection until the server is ready.
The sample's createFailoverPool keeps the process serving through a restart. It limits each connection attempt to five seconds and listens for ended connections. A request returns its own error; the next one opens a new connection. The sample's migrate retries lost connections at start for up to 120 seconds. A longer outage ends that start with failover_window_ended. The Database page describes both.
If the server's zone fails, its databases stay unavailable until that zone returns. The platform does not move them to another zone. An operator can restore a backup to a new server, but no recovery time is promised.
With pg alone or another driver, your code does the same three things itself:
- It listens for the pool's
errorevent. Without that listener, an ended connection stops the process. - It gives each connection attempt a timeout of a few seconds, so a request fails at once instead of waiting out the restart.
- It retries a lost connection during startup migrations for up to 120 seconds.
Without the Database package #
A server can use the pg driver alone, with no scaffold and no Database package. The sample below is one whole file. It reads the same two settings and does the three things the list above describes. It creates its table before it listens on PORT.
For migrations of your own, follow Work that needs one server session: use the direct setting for a lock held across transactions, or keep the lock inside each transaction.
For a complete app with ordered migrations, a public form and routes to read, change and delete entries, use Build a form backed by a database. It includes a deploy route for a tool with no shell.
// server.mjs: a server on the pg driver alone, with no scaffold and no Database package
import { createServer } from 'node:http';
import pg from 'pg';
// A request's abort signal. The deployed runtime attaches its own signal to each
// request, and it aborts at the request's window. A local run has none of its own,
// and Node's request.signal can abort at a normal request end on some Node 24
// releases, so a local run's signal aborts when the response closes unfinished.
function abortSignalOf(request, response) {
const own = Object.hasOwn(request, 'signal') ? request.signal : undefined;
if (own) return own;
const controller = new AbortController();
response.once('close', () => {
if (!response.writableFinished) controller.abort();
});
return controller.signal;
}
// The connection string carries sslmode=verify-full, so the pool takes no ssl option.
const url = process.env.APP_DATABASE_URL;
if (!url) throw new Error('APP_DATABASE_URL is not set');
// APP_DATABASE_CONNECTION_LIMIT sets its maximum.
// The platform supplies it; the turnzero command's provision writes it for
// a local run. The pool uses one connection where the setting is absent.
const limit = process.env.APP_DATABASE_CONNECTION_LIMIT ?? '';
const max = /^[1-9][0-9]*$/.test(limit) ? Number(limit) : 1;
// Each connect waits at most five seconds, so a request fails at once during a restart.
const pool = new pg.Pool({ connectionString: url, max, connectionTimeoutMillis: 5_000 });
// Without an error listener, a session the server ends stops the process.
pool.on('error', (error) => console.warn('database session ended:', error.message));
// The table, created at start. A lost connection is retried every second for up to 120 seconds.
const LOST = ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'EAI_AGAIN', '57P01', '57P03', '08006'];
const deadline = Date.now() + 120_000;
for (;;) {
try {
await pool.query('CREATE TABLE IF NOT EXISTS "notes" (id bigserial PRIMARY KEY, title text NOT NULL)');
break;
} catch (error) {
const lost = LOST.includes(error.code) || /timeout|terminated/i.test(error.message);
if (!lost || Date.now() + 1_000 > deadline) throw error;
await new Promise((resolve) => setTimeout(resolve, 1_000));
}
}
const port = Number(process.env.PORT ?? 8080);
createServer(async (request, response) => {
// End the response when the request is aborted (abortSignalOf, above).
const signal = abortSignalOf(request, response);
signal.addEventListener('abort', () => response.destroy(), { once: true });
const send = (status, body) => {
if (response.destroyed) return;
response.writeHead(status, { 'content-type': 'application/json' });
response.end(JSON.stringify(body));
};
const path = request.url.split('?')[0];
try {
if (request.method === 'GET' && path === '/health') {
await pool.query('SELECT 1');
return send(200, { ok: true });
}
if (request.method === 'GET' && path === '/notes') {
const { rows } = await pool.query('SELECT id, title FROM "notes" ORDER BY id');
return send(200, rows);
}
send(404, { error: 'not_found' });
} catch (error) {
console.error(error);
send(path === '/health' ? 503 : 500, { ok: false });
}
}).listen(port, () => console.log(`listening on ${port}`));
Its health path is /health, which the manifest's health member names. The health route runs SELECT 1 and returns 503 while that read fails. Change the route and the manifest together. With no library entry, the manifest's packages member is [].
If you add an absolute link to the deployed server, build it from APP_PUBLIC_HOST, even on a route that runs before sign-in. For this example’s notes route, use new URL('/notes', 'https://' + process.env.APP_PUBLIC_HOST).href. The request’s Host header names the internal router target. A deployed app’s settings lists the public hostname the platform supplies.
When the platform's abort signal fires, the sample ends the response, and send then writes nothing more. Node.js Runtime describes the signal.
The sample keeps no migration files. CREATE TABLE IF NOT EXISTS creates a missing table and leaves an existing table unchanged, so adding a column to that statement later does not update the table. Before changing the schema, use ordered migration files. The package-free pg helper in step 4 (Keep the schema as migrations) applies each file once, records it, and holds a lock so a second copy waits. You can also use the Database package's applyMigrations.
For offline data-layer tests with no library, sign-in or credential file, follow Without the Database package. That example runs the layer's SQL on PGlite directly through a query-only adapter. It does not test the pg driver or its connection behavior.
For the fuller pool interface and migration handling, take the Database package for its test double alone, as Use the feature package library describes; the server keeps importing only pg. The double ships inside the package, so the committed package copy gives every clone and CI run the same double, which runs without a Turn Zero credential.
An AI assistant with no shell or no CLI token can instead call tzcloud_read_library over its signed-in MCP connection to find the Database entry. It passes that entry's listed name in entry and reads lib/testing.js, lib/migrations.js, and lib/files.js by naming each path in file. The double runs PGlite, PostgreSQL inside Node.js, behind a pg.Pool-shaped interface.
The sample opens its pool and creates its table when it starts, so first move both into its entry block, as Write the data layer over a pool shows. Then give the double the table as a migration file, such as migrations/0001_notes.sql from step 2 (Connect to it). A local run needs neither change: it reaches the development database, as step 5 (Develop locally) describes.
CommonJS and Express #
For a CommonJS application using Express, save this as src/server.cjs. Keep the application's other dependencies and add express and pg. Set its start script to node src/server.cjs. The .cjs extension works without changing an ESM application's package type.
// src/server.cjs: CommonJS and Express, using pg without the Database package.
const express = require('express');
const pg = require('pg');
// A request's abort signal. The deployed runtime attaches its own signal to each
// request, and it aborts at the request's window. A local run has none of its own,
// and Node's request.signal can abort at a normal request end on some Node 24
// releases, so a local run's signal aborts when the response closes unfinished.
function abortSignalOf(request, response) {
const own = Object.hasOwn(request, 'signal') ? request.signal : undefined;
if (own) return own;
const controller = new AbortController();
response.once('close', () => {
if (!response.writableFinished) controller.abort();
});
return controller.signal;
}
async function main() {
const url = process.env.APP_DATABASE_URL;
if (!url) throw new Error('APP_DATABASE_URL is not set');
const limit = process.env.APP_DATABASE_CONNECTION_LIMIT ?? '';
const max = /^[1-9][0-9]*$/.test(limit) ? Number(limit) : 1;
const pool = new pg.Pool({ connectionString: url, max, connectionTimeoutMillis: 5_000 });
pool.on('error', (error) => console.warn('database session ended:', error.message));
const lostCodes = ['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'EAI_AGAIN', '57P01', '57P03', '08006'];
const deadline = Date.now() + 120_000;
try {
for (;;) {
try {
await pool.query('CREATE TABLE IF NOT EXISTS "notes" (id bigserial PRIMARY KEY, title text NOT NULL)');
break;
} catch (error) {
const lost = lostCodes.includes(error.code) || /timeout|terminated/i.test(error.message);
if (!lost || Date.now() + 1_000 > deadline) throw error;
await new Promise((resolve) => setTimeout(resolve, 1_000));
}
}
} catch (error) {
await pool.end();
throw error;
}
const app = express();
app.use((request, response, next) => {
// End the response when the request is aborted (abortSignalOf, above).
const signal = abortSignalOf(request, response);
signal.addEventListener('abort', () => response.destroy(), { once: true });
next();
});
const send = (response, status, body) => {
if (!response.destroyed) response.status(status).json(body);
};
app.get('/health', async (_request, response) => {
try {
await pool.query('SELECT 1');
send(response, 200, { ok: true });
} catch (error) {
console.error(error);
send(response, 503, { ok: false });
}
});
app.get('/notes', async (_request, response) => {
try {
const { rows } = await pool.query('SELECT id, title FROM "notes" ORDER BY id');
send(response, 200, rows);
} catch (error) {
console.error(error);
send(response, 500, { ok: false });
}
});
app.use((_request, response) => send(response, 404, { error: 'not_found' }));
const port = Number(process.env.PORT ?? 8080);
app.listen(port, () => console.log(`listening on ${port}`));
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
This variant keeps the same connection limit, startup retry, health check, and abort handling. It creates the initial table only; use step 4 (Keep the schema as migrations) before changing that schema.
3. Rotate the production credential #
If you think the production database password was exposed, follow the steps below to rotate it.
You can rotate the production database password for a server or a serverless version with functions.
A deploy or promote rotates the password only when you pass rotate_database_credential: true.
On an app with one environment, pass rotate_database_credential: true to tzcloud_deploy or tzcloud_deploy_command. If you use tzcloud_deploy_command, run the command it returns. For serverless, the command prepares the deploy before the platform has read the files. If the uploaded version has no function, the deploy is refused at start.
The chat deploy tool, tzcloud_deploy_files, does not take this option. To rotate from a chat on an app with one environment, turn on development first.
On an app with two environments, pass rotate_database_credential: true to tzcloud_promote. Deploy the version to development first. For serverless, use a version with functions that production does not serve yet. A promote of a serving function version fails before the password changes.
For a server, the role’s password changes before the new container starts. Between rotation and the switch, the old container's open connections keep working, but it cannot open new ones.
For a serverless version with functions, the password changes after the new settings are written and just before traffic switches. Until the earlier version stops taking calls, its calls that open a new database connection are refused.
A successful deploy or promote keeps the new password. If the deploy or promote fails after rotation, the platform restores the earlier password. A tzcloud_roll_back never rotates the database credential.
4. Keep the schema as migrations #
Keep schema changes as ordered .sql files in the application's migrations/ folder, named with zero-padded numbers that set their order. A server's start code applies them before it listens, with the Database package's applyMigrations, or code of your own. That code applies each file once, records it, and holds a lock while it runs. A second copy waits. The serverless route is below.
Code of your own on the pg driver alone can be one file, as below. It keeps the Database package's ledger table, schema_migrations, and the package's lock, so applyMigrations can take over later with nothing applied twice.
Both helpers below read migrations/ relative to the working directory, so start local runs at the application's root; the image runs npm start at /app, the deploy ZIP's root.
// src/migrate.mjs: applies each file of migrations/ once, in name order, under a lock, on the pg driver alone
import { readdir, readFile } from 'node:fs/promises';
import { join } from 'node:path';
// The Database package's ledger and lock, so its applyMigrations can take over later.
const LEDGER = 'schema_migrations';
const LOCK = "hashtext('mark_one_database_migrations')";
export async function migrate(client, folder = 'migrations') {
// One client, not a pool: an advisory lock belongs to the connection that takes it.
await client.query(`SELECT pg_advisory_lock(${LOCK})`);
try {
await client.query(`CREATE TABLE IF NOT EXISTS ${LEDGER} (name text PRIMARY KEY, applied timestamptz NOT NULL DEFAULT now())`);
const { rows } = await client.query(`SELECT name FROM ${LEDGER}`);
const applied = new Set(rows.map((row) => row.name));
const names = (await readdir(folder)).filter((name) => name.endsWith('.sql')).sort();
for (const name of names) {
if (applied.has(name)) continue;
// Remove leading whitespace, including a byte-order mark, before running the migration.
const sql = (await readFile(join(folder, name), 'utf8')).trimStart();
// Each file and its ledger row in one transaction, so a failed file records nothing.
await client.query('BEGIN');
try {
await client.query(sql);
await client.query(`INSERT INTO ${LEDGER} (name) VALUES ($1)`, [name]);
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK');
throw error;
}
}
} finally {
await client.query(`SELECT pg_advisory_unlock(${LOCK})`);
}
}
Call the migration helper at start, before the server listens, on a client of its own:
const directUrl = process.env.APP_DATABASE_DIRECT_URL;
if (!directUrl) throw new Error('APP_DATABASE_DIRECT_URL is not set');
const client = new pg.Client({ connectionString: directUrl });
await client.connect();
await migrate(client);
await client.end();
The helper holds its lock across transactions, so its client uses the direct setting. Unlike applyMigrations, it keeps no hash of each file, so it cannot refuse a file edited after it ran. Unlike the package's bootWalk, it does not retry a lost connection at start. Where a restart can meet the start, run it inside a retry like the one in step 2 (Connect to it).
CommonJS migration helper #
For the Express server above, save this helper as src/migrate.cjs. Its default migrations folder is relative to the process's working directory, so start the server from the application's root.
// src/migrate.cjs: applies each file of migrations/ once, in name order, under a lock, on the pg driver alone
const { readdir, readFile } = require('node:fs/promises');
const { join } = require('node:path');
// The Database package's ledger and lock, so its applyMigrations can take over later.
const LEDGER = 'schema_migrations';
const LOCK = "hashtext('mark_one_database_migrations')";
async function migrate(client, folder = 'migrations') {
// One client, not a pool: an advisory lock belongs to the connection that takes it.
await client.query(`SELECT pg_advisory_lock(${LOCK})`);
try {
await client.query(`CREATE TABLE IF NOT EXISTS ${LEDGER} (name text PRIMARY KEY, applied timestamptz NOT NULL DEFAULT now())`);
const { rows } = await client.query(`SELECT name FROM ${LEDGER}`);
const applied = new Set(rows.map((row) => row.name));
const names = (await readdir(folder)).filter((name) => name.endsWith('.sql')).sort();
for (const name of names) {
if (applied.has(name)) continue;
// Remove leading whitespace, including a byte-order mark, before running the migration.
const sql = (await readFile(join(folder, name), 'utf8')).trimStart();
// Each file and its ledger row in one transaction, so a failed file records nothing.
await client.query('BEGIN');
try {
await client.query(sql);
await client.query(`INSERT INTO ${LEDGER} (name) VALUES ($1)`, [name]);
await client.query('COMMIT');
} catch (error) {
await client.query('ROLLBACK');
throw error;
}
}
} finally {
await client.query(`SELECT pg_advisory_unlock(${LOCK})`);
}
}
module.exports = { migrate };
Add const { migrate } = require('./migrate.cjs'); beside the server's other imports. Replace its CREATE TABLE IF NOT EXISTS query inside the startup retry loop with this dedicated-client call. Keep the surrounding retry, and listen only after it succeeds. The migration client uses APP_DATABASE_DIRECT_URL because the helper holds its lock across transactions:
// Inside src/server.cjs's startup retry loop, within async function main().
const directUrl = process.env.APP_DATABASE_DIRECT_URL;
if (!directUrl) throw new Error('APP_DATABASE_DIRECT_URL is not set');
const client = new pg.Client({ connectionString: directUrl, connectionTimeoutMillis: 5_000 });
try {
await client.connect();
await migrate(client);
} finally {
await client.end();
}
Like the ESM helper, this helper uses one connection for its lock, records each file, and rolls back a failed file. It keeps no content hashes and does not retry by itself; the server's startup loop supplies the retry.
The platform provisions an empty database. This server's startup code creates and changes its tables, using the migration files in this example. The same files reach the development database at a local or deployed start, production at the start of the deploy or promote that reaches it, and the test double when it is created. A server's promote copies no schema and runs no migration itself: the new version's start code applies the files production lacks.
Records an application already kept in files reach the database the same way, as one migration file that carries them. Carry existing records into the database shows the file and the script that writes it.
applyMigrations applies each file not yet recorded in the schema_migrations table, each in its own transaction. If a file fails, startup fails, and earlier files stay applied. When copies start together, each transaction takes the same lock and reads the ledger again before applying a file. Running the function again is safe, and the sample's migrate runs it through the package's bootWalk, which retries a lost connection every second and fails startup with failover_window_ended after 120 seconds.
A file is applied in a database once that database's schema_migrations table records its name. The table also records a hash of each file's content, and a start that finds a recorded file edited fails before any file runs, naming the file. Edit a file freely until a database records it; the test double starts empty each time.
Where only the development database recorded it, edit it, then clear the development database as step 5 (Develop locally) describes, so the next migration walk applies the edited file. Once production has started a version carrying the file, a failed deploy included, never edit or rename it; add a new file.
A later change is a new file, such as migrations/0002_add_created_at.sql holding ALTER TABLE "notes" ADD COLUMN created_at timestamptz NOT NULL DEFAULT now();. A deploy or promote starts the new version beside the running one and switches only when the health path responds. So a migration runs against the database the old version is still using, and a failed deploy does not undo it. Write each migration so the running version keeps working until the switch:
- Add columns and tables before code reads them.
- Drop or rename only in a later version of your application, once no running version needs the old shape.
Save migration files as UTF-8 without a byte-order mark (BOM). Windows PowerShell shows how to avoid PowerShell 5.1's default BOM or UTF-16 output.
Serverless migrations #
For a serverless application, put each migration directly under the zip's root migrations/ folder, with a .sql extension. Nested files and files with another extension are ignored. Declare the database in the manifest and submit it before deploying. The serverless deploy's start checks, and deploy_files with check_only, refuse migrations_without_database before any write if the declaration is absent. check_deploy reads no zip.
At a deploy, the platform publishes the client files, provisions production's database if needed, and runs the migrations before the version serves. read_status and list_versions show the migrations step. The run uses the Database package's ledger, per-transaction lock and edited-file check, through one direct connection as your application's role. It checks the server's certificate against its name. The session starts with a thirty-second limit on each statement, including a wait on the walk's lock. A migration file can change or turn off that limit for the rest of the session.
PostgreSQL receives each migration file as one query, so a file can contain several statements and dollar-quoted ($$) PL/pgSQL function bodies. See The migration function.
A serverless deploy returns migrations_too_large when .sql files directly under migrations/ exceed 8 MiB in total, using the larger of each ZIP record's declared compressed and uncompressed sizes. The whole migration run has five minutes from the walk's start, including the files, the walk's own statements and lock waits. A file cannot extend this limit. Opening the connection has a separate ten-second limit.
The run receives at most 32 MiB from the database, including the walk's ledger read. Each file's statements together may return at most 10,000 rows or 16 MiB. Each of the walk's own statements may return at most 65,535 rows. Passing the run, answer or receive limits ends the session's connection and fails the act as migration_failed.
Promote and rollback use the migration files that version's deploy kept. They run against production's own database and leave development's untouched. A rollback skips recorded files and undoes none, so production keeps the schema the later version left. A restart or platform redeploy runs no serverless migration. After clearing development, run turnzero run --origin https://dev.turnzero.ai locally or deploy to development to rebuild its tables. The local command applies the same migration files before serving functions, using APP_DATABASE_URL and the application's own pg dependency. A local run needs no deployed development environment.
A failed migration fails the act and leaves the earlier version serving. Where none was serving, nothing serves afterwards. Files committed before the failure stay applied and recorded. Read detail and use query_database to inspect the database before retrying. Fix an unapplied file, or add a new file for a change to an applied migration. The next deploy applies only files still absent. Keep each migration compatible with the version still serving. Neither this run nor a promote takes a snapshot.
5. Develop locally #
To run a database app before its first deploy without platform services, follow Run against your own PostgreSQL.
Get the credential for a local run #
A local run reads the development database's credential from the settings file, .env by default. Over the HTTP API, a submission that names no local_run returns the development role's credential once. Through the Model Context Protocol (MCP) tool, and over the HTTP API where the submission names local_run, the response withholds it, because the platform never puts a platform-minted credential into an AI assistant's conversation.
The same file supplies APP_DATABASE_DIRECT_URL to turnzero db connect --environment development. Name a different file with --settings-file. The command uses the credential already on your computer and needs no browser approval.
With a shell that reaches the platform, your AI coding agent writes .env using its MCP sign-in alone, without computer sign-in or a minted token. It runs turnzero provision --origin https://dev.turnzero.ai --application <application id> with nothing piped, makes any printed tzcloud_submit_manifest call, then runs the returned provision command. That command uses this computer's verifier and prints no credential values. Run your app on your computer gives the steps.
If the development credential is lost later, your AI coding agent does the same again: the command calls HTTP store_secret with replace: true and environment: "development", which sets a new password on the role. Your AI coding agent leaves that call to the command. The MCP tool refuses it with local_route_required, and production refuses it with platform_minted_name.
A running development container keeps using its old, revoked credentials until it restarts. Where development runs a version, the command restarts it after creating the last replacement credential. Creating a replacement credential is called re-minting. The restart reads the new database connection string and platform credential from the platform's secret store. It does not count toward the day's deploys.
If a development deploy is still running, the response names tzcloud_restart_application on development. Your AI assistant makes that call once the deploy ends.
A local run that loads the development environment file reaches the development database, which is separate from production's on every application. The standing production connection string stays with the platform. The application's tests run on the package's test double and need no database. Use the development database for reset, seed, and other destructive experiments.
Run tests or check a deployed copy #
Tests need neither turnzero provision --origin https://dev.turnzero.ai nor .env. Taking the package needs a sign-in and the turnzero command, because npm carries no @turnzero package. The take line reads this computer's token, which login keeps, or a minted token. Run download.command_npx first, or its Windows form; for a refusal, see Running and writing lines. Once taken, npm test needs no account or connection (Test your application locally).
A tool without a shell cannot run tests or a local run. With development enabled, it deploys using tzcloud_deploy_files (Deploying from a chat whose shell cannot reach the platform). It uses tzcloud_request_route for GET and tzcloud_write_route for POST, PUT, PATCH or DELETE. It names environment: "development" on either call, then reads the rows with tzcloud_query_database in development (6. Read your data).
On an application with one environment, a deploy reaches production, so Test in development, then promote comes first. Where you ask for a fresh start, the tool requests tzcloud_clear_development_database and gives you the approval link. After the clear succeeds, follow Migrations, resets and data limits to rebuild the tables for your application's kind and environment.
Migrations, resets and data limits #
Keep schema changes in ordered migration files, noting any that remove or rewrite data. Read read_context with id guide:schema_evolution for development tasks: migrate, reset, seed, status, diff, and snapshot. Run them with your development tools; the platform supplies no such commands.
Reset development data through APP_DATABASE_URL, the connection string the provision command wrote into .env. Before the reset, your AI coding agent checks that no shell variable of that name exists, with the check the troubleshooting page Secrets gives. A shell value takes precedence over the file and could point to another application's database. Where the check shows the name, your AI coding agent tells you, and never resets under that value.
Your AI coding agent then clears the name and runs the reset in one command, since its next command can start a new shell that inherits the name again. For example, env -u APP_DATABASE_URL node --env-file=.env …, or in PowerShell Remove-Item Env:APP_DATABASE_URL -ErrorAction SilentlyContinue; node --env-file=.env … as one invocation.
In that command, the reset loads the string from the file as the local run does, and never prints the value or reads it into the conversation. Run your app on your computer describes the file.
To start development with an empty database, your AI assistant calls tzcloud_clear_development_database with application and environment: "development". Like a deletion, it needs a person's approval in the browser. Emptying the database cannot be undone, so the assistant waits for that approval. To delete only some development rows, use the application's own route or a migration, with no platform action. The approval page shows the database, its role, and the environment.
After approval, the platform drops the development database with every table and row in it, and creates it again empty under the same role. Open connections to it are closed. The role keeps its password, so the connection string in .env keeps working and the provision command need not run again. Keep the pending-action ID from the clear request and use it to call read_approval_status. Confirm pending_action.outcome.cleared: true before rebuilding the tables. The outcome gives the database and role names.
If a deploy, promote, or tzcloud_restart_application of the application starts while the clear runs, it waits for the clear to end, for 45 seconds at most. Past that, it fails, and you start it again. If any step of the clear takes longer than 20 seconds, the clear fails. The database may already have been dropped, along with every table and row. If you still want an empty database, request and approve a new clear. It creates an empty database. Any data dropped in the failed clear is gone.
The tables come back when the migrations run again. For a server, your AI assistant restarts development or deploys there, and the startup walk rebuilds the schema. For a server with production alone, the next local startup walk rebuilds the development database.
For a serverless application, run turnzero run --origin https://dev.turnzero.ai locally to rebuild the development database's tables, or deploy to development if that environment exists. The command applies .sql files directly under migrations/ before serving functions, through the application's own pg dependency. It uses APP_DATABASE_URL as the functions receive it, with the environment file's value taking precedence over the shell's. When migration files are present, a missing address, unavailable pg or failed migration stops the run before it serves. A restart or platform redeploy runs no serverless migration.
The clear is refused in three cases, and nothing is cleared:
production, with 400invalid_request. No action clears the production database.- An application with no development database, with 404
not_found. - A deploy or redeploy (a
tzcloud_restart_application) of development still in progress when the approved clear runs, with 409deploy_in_flight. Wait for it to end, then request the clear again.
To remove the whole development environment instead, use tzcloud_delete_environment, as Delete the development environment describes. On an application with one environment, the same call removes the development database and every other record your local runs keep: the credentials, the stored secrets, the files, and the logs. Production is untouched. Then call tzcloud_submit_manifest naming no local_run to set the database up again, and run turnzero provision --origin https://dev.turnzero.ai --application <application id> with nothing piped, and make any call it prints.
A promote takes no snapshot, and a tzcloud_roll_back restores the earlier version's code, setting bindings and plain values. A migration the new version applied stays applied when you roll the code back. So write migrations the previous version can run against, or plan how to migrate or restore the data before you roll back. The reserved HTTP actions apply_migration and restore_snapshot return 501 not_yet_provisioned. For a dedicated production database, see Restore a dedicated database.
The platform measures each database's size daily. It counts toward the application's stored-data ceiling and posts a day's share on the database storage line (Size and usage). Read the rate on the pricing page or with read_rate_card.
6. Read your data #
Ask your AI to run a read-only SQL query, or open PostgreSQL tools on your computer to work with the database yourself.
For a query in chat, your AI assistant calls tzcloud_query_database with application and one SQL statement in sql. Without environment, it reads production. With environment: "development", it reads the database used by your local runs. To compare environments, name one in each call, including environment: "production".
Run SELECT version() in each environment you use to check its PostgreSQL version. Development and production can run different versions during an upgrade.
To work interactively, import or export, follow Connect to your database. Approve a temporary production connection in your browser or use the application’s development credential for development.
For example, sql: "SELECT count(*) FROM comments" answers columns: ["count"], rows: [["42"]], row_count: 1, and truncated: false. Each value comes back as PostgreSQL's text for it, such as "42" for a count, or as null.
The statement starts with SELECT, WITH, VALUES, or TABLE. It runs as the environment's own database role, inside a read-only transaction that is always rolled back, so it changes nothing. A write, such as INSERT, UPDATE, DELETE, or CREATE, is refused query_not_read_only, and so is a write inside a function the statement calls. One call runs one statement.
The answer is bounded. It carries at most limit rows, 100 where you give none and 1,000 at most, and at most 64 KiB of row data. The statement runs for 10 seconds at most. Where a bound cut the answer, truncated says which, "rows" or "bytes", and it is false where nothing was cut.
For "rows", order by a stable, unique key and start the next page after the last key returned. For "bytes", select fewer or smaller columns. The byte limit can omit a large row even when the query matches only one.
tzcloud_query_database is an observe-tier action, so it needs no approval. Only your own account can call it. Neither the statement nor the rows it reads are written to the platform's logs.
Check data after a restart or idle stop #
Use an existing record to check persistence without adding test data to production. These calls also work in an AI assistant with no shell.
Choose the application and environment. Use
tzcloud_query_databaseto read stable fields of an existing record by its identifier, and keep the result for comparison. Name that same application and environment in every call. If no record exists, use an approved development test instead, or report that there is no data to check.For a restart test, call
tzcloud_restart_applicationonly when the person has asked for the test, and follow its returned status read until it finishes. For an idle test, use an environment that stops when idle, production withproduction_sleepon, or a development environment (Start after idle and response time), and let it idle normally.Read
tzcloud_read_logswithsource: "container"until itsdetailconfirms that the environment is idle and scaled to zero. Look for that confirmation in responses that include log lines. Status and console reads do not wake it. Application requests and scheduled runs can keep it awake; elapsed time orcompute_state: "Idle"alone does not prove an idle stop.After an idle stop, call a known read-only application route with
tzcloud_request_routeto start it again. Then repeat the same database query and compare the saved fields. After a restart, repeat the query once the restart has finished.
Report the event you observed and the before-and-after values. If the console does not confirm an idle stop, report that the idle check is unverified. This checks the selected record, not every row or a backup restore.
Durability and backups #
Automatic backups are kept for 35 days, with copies in a second United States region, for every application. Data survives idle stops, restarts, deploys and promotes.
An operator can restore one database to a chosen time in that window. For a shared database, email support@turnzero.ai with the application, the environment and the UTC instant to restore to.
Deleting an application, an environment or an account, or clearing the development database, removes that data. Backups cannot restore it. Save an export before deleting or clearing data.
Restore a dedicated database #
Ask your AI assistant to restore your application's dedicated production database to a specific time. A successful restore uses the schema and data as they were at that time. It discards later changes, including inserts, updates and deletes made while Turn Zero prepares the restored copy.
Before asking for approval, check the time, the serving version, and how you will verify the result.
- If the owner says “yesterday,” confirm their time zone and when the data was last correct. Show them the exact time in both local time and UTC.
- Check that the version serving production can use the schema and data at that time. If a migration is involved, follow the compatibility steps below before requesting the restore.
- Agree on a read-only query to check the rows or counts the owner needs back. Run it after
tzcloud_read_statusshowsdonefor the matching production move, and confirm that the expected version is serving.
- Choose a time with the owner. Use UTC to the second (
YYYY-MM-DDTHH:MM:SSZ), at least five minutes ago and within the last 35 days. The time must be at or after the server's creation and when the database began serving there. Confirm it with the owner before asking for approval. - Request the restore and hand over the approval link. Call
tzcloud_restore_databasewithapplicationandpoint_in_time. The owner approves in a browser. Useread_approval_statusto follow the request. A successful approval outcome confirms the restore started. Keep its move ID. - Follow that move to its end. Read the application's production
database_movewithtzcloud_read_statusand match its ID. Whenoutcomeisdone, check the expected data with a read-only query. If it endsreverted, report that the restore did not complete and production uses the original database.
If the request returns restore_instant_before_serving, choose a time at or after the switch time in the response. If it returns restore_serving_since_unknown, contact support. The platform has not started a restore.
Turn Zero prepares a dedicated server of the same size while production continues to serve. Production is unavailable from the freeze until the serving version restarts or the restore reverts and lifts the freeze. A restore costs nothing extra. You are not charged for the second server or for the copy kept for one day.
The restore removes any earlier move's kept copy first. After success, Turn Zero keeps the original database for a day unless another move ends it sooner. There is no action to switch back to it. A later restore cannot reach a time before the switch to the restored database.
For a server, restarting the serving version can run a startup migration again if the restored database has no record of it. The platform's restart of a serverless version runs no migration files.
Before restoring an earlier schema, check that the version serving production can use it. To undo a migration, roll back to a compatible version without the migration and confirm that version is serving. Then restore to an allowed time before the migration's applied time in schema_migrations.
Database sizes #
Every new database uses database-shared. Its production and development databases use shared servers in the application's cell. A server or serverless application can move its production database to a dedicated PostgreSQL server in the same cell and region. Development stays shared. A billed account can choose only a size opened to it.
| Dedicated size | Memory | CPU cores |
|---|---|---|
database-dedicated-2gb |
2 GiB | 1 |
database-dedicated-4gb |
4 GiB | 2 |
database-dedicated-8gb |
8 GiB | 2 |
These servers have burstable CPU. After their CPU credits are spent, they run at their base CPU share. The core count is not a promise of sustained full-core performance.
Each dedicated size has its own connection limit. For a server, set each process’s pool maximum from APP_DATABASE_CONNECTION_LIMIT. tzcloud_read_status gives that quantity as connection_limit. On a dedicated database the server’s APP_DATABASE_URL and APP_DATABASE_DIRECT_URL both use direct port 5432. A function receives APP_DATABASE_URL on the same port and should use at most one connection per worker.
For a server app outside the Unlimited plan, the move back keeps the direct address initially. A new production deploy uses pooled port 6432, and a promote uses it if the version recorded it. Restarting the serving version alone keeps the direct address. A serverless app gets port 6432 when the move restarts production. Server apps on the Unlimited plan keep direct port 5432. Check work that needs one server session before returning to transaction pooling.
Changing size requires the owner's browser approval of tzcloud_set_database_size. Production is unavailable from the freeze until its serving version restarts successfully or a revert restores the source. A production deploy or promote is refused with database_move_in_flight throughout the move, including server preparation. Repeat the refused act after the move ends. Production gets a new password and host. The connection limit comes from the target's configured quota and may change. The application, hostname, environments, code, database and role names, setting names, development database and stored files stay.
The 35-day, geo-redundant backups described above also cover a dedicated database. Its server runs in one zone; a host failure can restart it. Scheduled maintenance is Sunday, 14:00–15:00 UTC.
A dedicated database is charged daily at the day’s share of its size’s monthly rate. The daily billing run is scheduled for 03:00 UTC and adds the charge for the UTC day it runs in. That charge also covers development. Charges already made stay on your account when you leave a size. At the first daily billing run after the move, the application stops counting toward the shared database charge. Shared database charges already made stay on the account.
Choose a dedicated database explains the approval, interruption, move back and charges, with links to current rates.
Expected result #
tzcloud_submit_manifest returns outcome: "recorded" and, once the development database exists, development_database with host, dbName, roleName, and connection_setting: "APP_DATABASE_URL", and connection_limit beside it. Through the MCP tool, the first submission states credentials: "withheld".
The provision command then prints the settings it wrote, each credential value as a count of characters, then a line about the development database. .env then contains APP_DATABASE_URL, APP_DATABASE_DIRECT_URL and APP_DATABASE_CONNECTION_LIMIT, and the start code prints migrations applied at this start: 0001_notes.sql at its first start.
tzcloud_read_status returns connection_limit beside size, and each environment's database, or null where the environment has none. With tables: true, it also lists each database's table names. Without environment, the top-level database and tables members describe production, and are null until the first deploy or promote that reaches production; with environment, they describe that environment, which the top-level environment member gives.
tzcloud_query_database returns the statement's columns, its rows, row_count, and truncated, and the database is unchanged.
Check database size and connections #
Ask your AI to call tzcloud_read_status with database_reading: true. Each environment gets its own reading. The top-level application object gives the reading for the environment the answer describes. Use read_at to see when it was taken. The reading is a snapshot of current sessions and keeps no history.
The reading gives size_bytes for the environment’s database and says whether its server is shared or dedicated. connections counts the database role’s active sessions, idle sessions and sessions idle in a transaction, and gives the role’s connection limit if it has one. On a shared server, connections through the pooled port appear as the pooler’s sessions with the server for that role. The count also includes the role’s direct sessions for that database. Clients still waiting in the pooler are outside that count.
long_running shows up to five sessions that have been active or idle in a transaction for at least five seconds, longest first. It gives each session’s state, its time in seconds and the first 200 characters of the statement when the server supplies it.
On a dedicated server, disk.size_bytes is the recorded disk size and can lag automatic growth. disk.used_bytes adds up the bytes in the server’s databases and excludes the write-ahead log. On shared servers disk is null.
If the environment has no database or the reading fails or times out, status still returns. database_reading is null and database_reading_error gives no_database or database_read_failed.
Refusals #
See the refusals reference for other platform errors.
The refusal tables below list errors from the database declaration, the provision command's HTTP store_secret calls with replace: true, tzcloud_set_app_size, tzcloud_clear_development_database, and tzcloud_query_database. Author the manifest lists the manifest's other refusals, Deploy from your computer the deploy's and the promote's, and Run your app on your computer the provision command's grant refusals.
A refusal gives its cause in detail. A refused HTTP store_secret with replace: true changes no credential, and a refused tzcloud_set_app_size records no size or sleep change. The tzcloud_submit_manifest refusals below happen after the manifest is recorded and before the development database is ready.
Database operations #
| Refusal | Status | Cause | Remedy |
|---|---|---|---|
invalid_request |
400 | detail names the missing or malformed member. HTTP store_secret with replace: true refuses an environment other than development or production. tzcloud_clear_development_database refuses production; no action clears it. |
Correct the named member. |
query_not_read_only |
400 | tzcloud_query_database's statement would write: its first word is not SELECT, WITH, VALUES, or TABLE, or the read-only transaction refused a write inside it. Nothing changed. |
Send a statement that only reads. Make changes through your application's own routes or migrations. |
not_found |
404 | HTTP store_secret with replace: true named the development database credential of an application with no development database, or a name not stored. tzcloud_clear_development_database named an application with no development database. tzcloud_query_database named an environment with no database. |
Submit a manifest that declares the database first. For tzcloud_query_database on production, deploy or promote to production first. |
plan_quantity_unset |
409 | A required quantity for the size is unset. The manifest stays recorded. | Read its row with tzcloud_read_plan_quotas and wait for platform staff to set it. |
deploy_in_flight |
409 | A deploy or redeploy (a tzcloud_restart_application) of development was in progress when the approved tzcloud_clear_development_database ran, so nothing was cleared. |
Wait until tzcloud_read_status shows it ended, then request the clear again. |
deletion_in_progress |
409 | The application or one of its environments is being deleted. If you approve a deletion while an earlier deletion still holds the same application, the new deletion fails with this refusal. That refusal's detail gives the instant the other deletion's hold lapses; if its process stopped, request your deletion again after that instant. | Wait for the deletion to finish; read_approval_status shows whether it completed. If it failed, request the same deletion again to complete it. |
query_failed |
422 or 503 | tzcloud_query_database's statement or its session failed. At 422, the database server refused the query. The answer gives its sqlstate and message. Common codes include 42601 for a second statement, 57014 for the 10-second limit, 53300 where the role's connections are all in use, and 42P01 for a missing table. At 503, the session failed without an answer from the server: it never reached it, or it ended mid-statement at the 15-second limit or on a network drop. |
At 422, correct the statement, or narrow it to finish within 10 seconds. For 53300, call again once your application frees a connection. For 42P01, check the table name. If you just deployed, its migrations may still be pending. Check tzcloud_read_status and retry once the new version is serving. At 503, call again later. |
database_provisioning_failed |
502 | tzcloud_submit_manifest could not create the role or password, though the manifest stays recorded. HTTP store_secret with replace: true found a recorded development database with no role and changed nothing. |
After submit_manifest, retry the same manifest once any deletion ends. If store_secret reports a missing role and you need to keep the data, report the reference. A reset removes development data, secrets, files, and logs. Reset only if the owner chooses it and approves delete_environment in the browser. For an application with two environments, call tzcloud_create_environment before resubmitting. Report a failed reset with its reference. |
entitlement_apply_failed |
502 | A compute or connection-limit write failed; the size and sleep setting were not recorded. | Repeat the same tzcloud_set_app_size call. Report a repeated failure with its reference and detail. |
server_unavailable |
503 | tzcloud_submit_manifest: no server has room, or an unfinished setup recorded a server that no longer accepts databases; that record prevents moving the setup. The manifest stays recorded. On a promote or production deploy, the same refusal ends the record failed at database_pair. |
After tzcloud_submit_manifest, check the current setup before resubmitting. Wait for a running setup. If no server has room or the outcome is unclear, report the refusal. If the owner chooses to remove a stopped setup, explain that tzcloud_delete_environment for development removes its data, credentials, files and logs on one environment or two. Get browser approval and check its outcome. On two environments, call tzcloud_create_environment before resubmitting. After a promote or production deploy, report an earlier run to platform staff. Resubmit after staff remove the earlier setup or reopen the server only if the work is still needed. |
cell_not_configured |
503 | The platform cannot place the database now; the manifest stays recorded. A promote or a production deploy whose production database has no placement ends failed the same way at its database_pair step. |
Nothing on your side corrects this: report the refusal with its detail, and repeat the action once platform staff have configured the hosting cell. |
Credentials and local provisioning #
| Refusal | Status | Cause | Remedy |
|---|---|---|---|
authentication_required |
401 | An unattended provision sent no minted token, or one that matches no account. |
Set TURNZERO_CLOUD_MINTED_TOKEN to a token minted for the application. |
token_scope_refused |
403 | The script's token is for one application, and the request named another. | Mint the token for the application the request names. |
app_credential_not_admitted |
403 | An unattended provision ran under the application's platform credential, such as a TURNZERO_CLOUD_APP_TOKEN copied from .env into TURNZERO_CLOUD_MINTED_TOKEN. The platform credential can call read_account. Storage, logging, egress, push, email, and end-user verification admit the credential on their runtime routes. The unattended provision needs the application-bounded minted token below. |
Set TURNZERO_CLOUD_MINTED_TOKEN to a token bounded to the application, minted with mint_token from your signed-in session. Then run the command again. |
platform_minted_name |
409 | HTTP store_secret with replace: true named database-<application id> or credential-<application id> on the production scope, or tzcloud_store_secret named either. |
Run turnzero provision --origin https://dev.turnzero.ai --application <application id> with nothing piped and make any call it prints. If development runs a version, restart it with tzcloud_restart_application; this takes both re-minted credentials without using a daily deploy. For a server or a serverless version with functions, rotate production's credential with rotate_database_credential: true on a production deploy or promote. |
serverless_unsupported |
403 | Rotation was requested for a serverless version with no functions. The promote refuses before recording a version. The deploy refuses at start after upload and records no version. The password and serving version stay as they were. | For a promote, omit rotate_database_credential and repeat the call. For a deploy, make a new tzcloud_deploy or tzcloud_deploy_command call without it. A refused start with an upload grant spends the grant and offers no start-only retry. |
local_route_required |
409 | tzcloud_store_secret with replace: true named a platform-minted name on the development scope through the MCP tool. |
Run turnzero provision --origin https://dev.turnzero.ai --application <application id> with nothing piped and make any call it prints; its line uses the HTTP API. If development has a running version, call tzcloud_restart_application there afterwards. It takes both re-minted credentials without using a daily deploy. |
rotation_in_flight |
409 | Another HTTP store_secret with replace: true call for the same development database credential was still running, so nothing changed. |
Wait for that call to finish, then run turnzero provision --origin https://dev.turnzero.ai --application <application id> with nothing piped and make any call it prints. The line writes the current password. If development runs a version, restart it with tzcloud_restart_application; this takes both re-minted credentials without using a daily deploy. |
database_credential_unreadable |
502 | A deploy, promote, rollback, platform redeploy, or tzcloud_query_database could not read the stored database credential. A version already serving stays in place; where none was serving, none serves afterwards. |
Retry. If it repeats for development, run turnzero provision --origin https://dev.turnzero.ai --application <application id> with nothing piped. Follow Restore access to a database credential for the remaining development steps or a repeated production refusal. |
Restore access to a database credential #
Retry the original action first. If database_credential_unreadable repeats for development, follow steps 1 to 4. For production, follow steps 5 to 7.
Run
turnzero provision --origin https://dev.turnzero.ai --application <application id>with nothing piped.Make any printed
tzcloud_submit_manifestcall through your signed-in connection, then run the returned provision command on the same computer. With no shell, ask the person to run the command on a computer with a shell and paste the printedtzcloud_submit_manifestcall into this chat. Make that call through your own connection, then ask them to run the returned command on that same computer.The command replaces the development credential. Where development serves a version, the command restarts that version; it does not deploy the failed version. Where nothing serves, it restarts nothing, and the next development deploy takes the new credential. Follow any instruction to restart once an in-flight deploy ends, as Develop locally describes.
After a failed deploy, deploy development again with the same files; after
tzcloud_query_database, retry that query. If the refusal repeats after successful provisioning, follow the production report route below.For production, including a first deploy, promote or rollback, provisioning development does not repair it. For a repeated production refusal, call
submit_feedbackwith the refusal. For a failed deploy, promote or rollback, quote that call’s returnedreference, not a laterread_statuscall’s. For another failed call, quote itsreferencewhere returned. Platform staff restore access to the credential for either environment.Passing
rotate_database_credential: truedoes not repair this refusal: the platform reads the standing credential before rotating it.Keep the returned issue id and call
read_feedbackwith it. Readnote_to_reportersandlive_in;fixedmeans built and being released. Follow the platform’s recovery instructions, and retry the original action only after it confirms credential restoration or that the fix is live.
Migration refusals #
These refusals concern serverless applications. migrations_without_database can refuse the deploy's start checks or deploy_files with check_only before the deploy starts. check_deploy reads no zip.
migration_edited, migration_failed and migration_busy appear as error and detail in a failed deployment row, read through read_status or list_versions. They do not replace the initiating call's accepted response with an HTTP error status. The table marks them as failed-row errors.
| Refusal | Delivery | Cause | Remedy |
|---|---|---|---|
migrations_without_database |
HTTP 400 before the deploy starts | A serverless zip has migration files but the recorded manifest declares no database. The deploy's start checks or deploy_files with check_only wrote nothing. |
Declare and submit the database, or omit migrations. Check and deploy again. |
migrations_too_large |
HTTP 400 before the deploy starts | The .sql files directly under migrations/ exceed 8 MiB in total, counting each record's larger declared compressed or uncompressed size. Nothing was written. |
Keep the migration records within the named bound and put seed data elsewhere. Check and deploy again. |
migration_busy |
Failed-row error | No migration slot is free for the management service or the owning account. This run opened no migration connection and applied no file. The earlier version keeps serving. | Wait a moment, then repeat the failed deploy, promote or rollback. |
migration_edited |
Failed-row error | A serverless migration differs from the database's recorded hash. This walk committed no file. The earlier version keeps serving. Where none was serving, nothing serves afterwards. | Restore the applied file and add a new migration for the change. If only development recorded it, clear that database after browser approval, then deploy again. |
migration_failed |
Failed-row error | A serverless deploy, promote or rollback failed at migrations. Read migration_failed and detail in its failed version row through read_status or list_versions. detail gives the file and SQLSTATE when available. Causes include a missing database, a statement cancellation, a connection failure or ten-second opening timeout, or a run, answer, receive or row limit. Earlier committed files stay applied. The earlier version keeps serving; where none was serving, nothing serves. |
Read detail and inspect the database with query_database. For a connection failure or run limit, repeat the failed deploy, promote or rollback; only absent files run. For 57014, shorten the statement or retry after the lock is free. For an answer or receive limit, remove large queries. Split a file that cannot finish alone within five minutes. Change only unrecorded files; otherwise add a new one. If only development recorded the file, clear_development_database can delete its data and migration records after browser approval; wait for completion before editing. Deploy changed files to development, then promote, or deploy to production if development is off. Report a ledger over 65,535 rows with submit_feedback; never delete migration records to retry. With no database, declare it or omit migrations, then deploy. Rollback undoes no migration. |
Related #
- Database describes what the package provides, its migration function and failover pool, and its availability.
- Build a database-backed service writes a new service with this page's data module, its server, and its tests.
- Run your app on your computer runs the application locally on the file the provision command writes.
- Test your application locally runs the application's tests on the package's test double, with no database.
- Test in development, then promote covers the promote that creates the production database on two environments.
- The deploy health check explains the check a new copy must pass while its migrations run.
- Choose a dedicated database explains the production move, its connection changes, interruption and charges.
- Size and usage covers sizes,
tzcloud_set_app_size, and usage. - Stay inside the Free Allowance checks the database and other charges against the account's Free Allowance.
- tzcloud_submit_manifest, tzcloud_store_secret, tzcloud_read_status, and tzcloud_set_app_size in the generated reference give each action's arguments and result.