---
title: Connect to your database
description: Use PostgreSQL tools on your computer to restore, export, or inspect your application's development or production database.
slug: /guides/connect-to-your-database
order: 32
visibility: public
redirects_from: []
---

# Connect to your database

Prompt:

> Restore my PostgreSQL dump into my app. Check the target with me before you connect to production.

Run `pg_restore`, `pg_dump`, or `psql` from your computer against an application database. For development, the command uses the credential already on this computer. For production, it uses a temporary connection that you approve in the browser.

If a single bounded SQL statement can answer your question, use the [read-only query action](/cloud/guides/add-a-database/#6-read-your-data) with the intended environment. Use a PostgreSQL client when you need an interactive session, export, or restore.

## Before your AI starts

For the AI assistant:

- Confirm the application, target environment, dump format and source, and what may change. Test against development first. Inspect SQL from an unfamiliar source. If it creates extensions, check that the destination allows them.
- For development, use the file written by [`turnzero provision --origin https://dev.turnzero.ai`](/cloud/guides/add-a-database/#get-the-credential-for-a-local-run). Check that it contains `APP_DATABASE_DIRECT_URL` without displaying its value. For production, check that a deploy or promote has provisioned the database. Use a signed-in Cloud connection to request approval. The terminal also needs its own credential for the same account. The command uses a configured minted token first, then this computer's saved Turn Zero sign-in.
- Check that this computer has the `turnzero` command and PostgreSQL client tools. Development needs client tools version 16 or later for certificate verification. Check the server with `SELECT version()` through the [read-only query action](/cloud/guides/add-a-database/#6-read-your-data). Name the environment you will connect to.
- For a custom archive, use a `pg_restore` version that can read it. `pg_restore --list` shows which `pg_dump` version wrote it. An older destination server may still refuse SQL the archive contains. Use the person's terminal if your chat has no shell or the file is on their computer.

## Steps

### 1. Ask for the production connection

For development, go straight to [step 2](#2-run-one-postgresql-tool). The command uses the credential in the local file. It makes no platform request and needs no token or browser approval.

For production, call `open_database_connection` with the application identifier. Show the person the approval link and name the database and the tool you intend to run. The account owner approves in the browser. The approval names the application and describes a one-hour connection. The browser shows this question.

> Open the production database of {application} for one hour? Any program run through this connection can read, change or delete every row in it.

Use the pending action's ID as `--grant`. The command waits up to one hour for approval and stops sooner if the request expires. If it stops waiting, check the approval's state before asking for another. One approved production connection can be open for an application. The PostgreSQL sessions within it share the limit in [Connection settings and limits](#connection-settings-and-limits). A new grant ends the open connection. A database move blocks a new connection and ends a standing one. Deleting the application also ends it. After the tool exits, read the command's final message to check whether the platform ended the connection.

### 2. Run one PostgreSQL tool

The commands below work with shared and dedicated databases on both server and serverless apps.

Check your local PostgreSQL tool's version with `--version`, for example `pg_restore --version`. To export with `pg_dump`, use a tool on the server's PostgreSQL major version or a newer one. An older `pg_dump` refuses a newer server.

On Windows PowerShell, use `turnzero.cmd` ([Windows PowerShell](/cloud/getting-started/prerequisites/#windows-powershell)). In Git Bash, use `turnzero` if the command is on your `PATH`. On Windows, put the PostgreSQL executable after `--`, such as `psql.exe` or `pg_restore.exe`. The command cannot start a `.cmd` or `.bat` wrapper there.

For development, run from the folder that holds the provisioned `.env`. If you use a different file, add `--settings-file ../.env.turnzero` before `--`. Use an absolute path or a path from this folder for any input or output file.

For production, replace `PENDING_ACTION_ID` with the pending action's ID. Request a fresh approval before running another tool after the first exits. Use only one connection option per call.

When your target is production, use the production restore command for your dump format. A promote moves application code to production and leaves development data in development.

#### Restore a custom-format archive

Start with an empty target when possible. The empty `--dbname=` uses the database name the command provides. The ownership and privilege flags skip source owners and privileges.

On development, run this command.

```text
turnzero db connect --environment development -- pg_restore --dbname= --exit-on-error --no-owner --no-privileges "source.dump"
```

On production, use the pending action's ID.

```text
turnzero db connect --grant PENDING_ACTION_ID -- pg_restore --dbname= --exit-on-error --no-owner --no-privileges "source.dump"
```

#### Restore plain SQL

Use a SQL file prepared for the existing database and role on the destination. These commands stop at the first SQL error.

On development, run this command.

```text
turnzero db connect --environment development -- psql --no-psqlrc --set ON_ERROR_STOP=on --file "source.sql"
```

On production, use the pending action's ID.

```text
turnzero db connect --grant PENDING_ACTION_ID -- psql --no-psqlrc --set ON_ERROR_STOP=on --file "source.sql"
```

#### Export a custom-format archive

Choose a path for the database copy. When exporting a large custom-format archive through `turnzero db connect`, pass `--compress=0` to `pg_dump`.

On development, run this command.

```text
turnzero db connect --environment development -- pg_dump --format=custom --file "development.dump"
```

On production, use the pending action's ID.

```text
turnzero db connect --grant PENDING_ACTION_ID -- pg_dump --format=custom --file "production.dump"
```

#### Open an interactive session

On development, run this command.

```text
turnzero db connect --environment development -- psql --no-psqlrc
```

On production, use the pending action's ID.

```text
turnzero db connect --grant PENDING_ACTION_ID -- psql --no-psqlrc
```

Use `\conninfo` and `SELECT current_database(), current_user;` to check the database and role. Enter `\q` to end the session. The production form connects through a local listener, so a loopback host is expected there.

### 3. Verify the result

Check the tool's exit status first. For a restore, compare row counts or known records in the expected tables before using the data. The read-only [query action](/cloud/guides/add-a-database/#6-read-your-data) can check results within its limits. For an export, run `pg_restore --list` on the archive the tool wrote.

## Remove test rows when the app has no delete route

Only the account owner can start this cleanup, by requesting it. A test never uses this procedure to delete rows from production. If the app has no delete route, the test leaves the rows and reports them to the owner.

1. After the owner requests cleanup, use the test report to find the test user and the route that wrote the rows. Use the [read-only query action](/cloud/guides/add-a-database/#6-read-your-data) on production to confirm the exact IDs and how you know they came from that test. Stop if you cannot identify them.

2. Show the owner the intended rows. Get the owner's browser approval in [step 1](#1-ask-for-the-production-connection). [Open `psql`](#open-an-interactive-session) and confirm the database and role. Check which related rows a delete could change through foreign keys or triggers. Stop if any effect is unclear.

3. In that same session, run `BEGIN` and recheck the rows. Before deleting, use `\copy` to save every row you will delete and each related row the delete will change. Save the files outside the application's folder, so no deploy includes them, and check them on your computer. Delete the files once the owner has confirmed the result and no longer needs them. Delete only the verified IDs that still match the test marker.

4. Show the owner the IDs from `RETURNING` and the results of your checks on related rows. Run `COMMIT` only when the owner tells you to commit. If anything differs or the owner does not confirm, run `ROLLBACK`.

Repeat the read-only check after committing. A [database restore](/cloud/guides/add-a-database/#durability-and-backups) takes the entire database back to an earlier time. It cannot undo just this delete.

## Connection settings and limits

**From deployed code.** Your server uses `APP_DATABASE_DIRECT_URL` when it needs a direct session to its own environment’s database. On dedicated production, the server’s `APP_DATABASE_URL` also connects directly. Hosted functions use `APP_DATABASE_URL` alone. It connects through the pooler on a shared database and directly on a dedicated database. The platform opens the direct connection for their migrations.

The command clears inherited `PG*` settings and starts the PostgreSQL tool directly. It leaves its own credential variables out of the tool's environment. Keep connection credentials out of commands and transcripts. The tool runs as the application's role on its own database.

For development, the command reads `APP_DATABASE_DIRECT_URL` from the provisioned file. It sets `PGHOST`, `PGPORT`, `PGUSER`, `PGPASSWORD`, and `PGDATABASE` from that string. It also uses the string's `sslmode` as `PGSSLMODE`. With the provisioned `verify-full` mode, the tool verifies the database certificate against this computer’s trusted roots. The command sets `PGSSLROOTCERT=system` by default. On Windows, if the trust store contains root certificates, the command passes them in a temporary file and removes it when the tool exits.

For production, `PGHOST` is `127.0.0.1` and `PGPORT` is a local port. The command passes the name in `PGDATABASE` and the temporary login in `PGUSER` and `PGPASSWORD`. The standing production credential stays with the platform. The connection uses a direct database session outside the application's hosted pool.

The production command creates the password on your computer, keeps it in memory, and sends its verifier to the platform. `PGSSLMODE=disable` applies to the loopback hop. The command connects to the platform over HTTPS, and the platform verifies the database server's name over TLS.

The production connection lasts up to one hour from when the approved action opens it. The command prints its expiry before starting the tool. It admits four database sessions at once. Use at most three parallel `pg_restore` jobs so its coordinating session can connect.

When the tool exits, the command closes its local connection and asks the platform to end the approved connection. Check the command's final message. If the command cannot confirm the end, the approved connection may remain open until its expiry.

An index build can reach the server's 256 MB temporary-file limit. If that happens, identify the failing operation in the tool's error before planning another attempt. An inherited `PGOPTIONS` setting for `maintenance_work_mem` will be cleared before the tool starts.

## If a connection ends early

For production, expiry, a platform release, a scale-in, or a move can interrupt the tool. During a platform stop, a connection may remain open for up to about nine and a half minutes. A restore that committed several transactions leaves those transactions in place.

On either environment, check the result before retrying. For production, get a fresh approval. Turn Zero Cloud has no action to empty the production database. For a custom archive, `--clean --if-exists` drops the objects the restore will replace. Confirm which objects the owner wants replaced. For plain SQL, inspect which statements ran before choosing where to resume.

## Expected result

The command prints the database and role without the password, runs the tool against the selected database, and returns the tool's exit status. For a development connection, it also prints the server and port before starting the tool and warns if the TLS mode is weaker than `verify-full` or unrecognized. A successful export leaves an archive on your computer. A successful restore leaves the tables and data checked in step 3.

## Refusals

| Refusal | Status | Cause | Remedy |
| --- | --- | --- | --- |
| `database_move_in_flight` | 409 | A move of the production database or a move of the application between cells is still in progress. | Wait for the move to end, then check the target before requesting another connection. |
| `database_not_provisioned` | 409 or pending action outcome | The call found no provisioned production database, or the approved action found that the recorded database or role is missing from its server. | If production has no version that declares the database, [declare it](/cloud/guides/add-a-database/#1-declare-it) and deploy or promote that version. Wait for it to serve, then request the connection again. If the pending action's outcome says the database or role is missing, report its detail and pending action ID. Include the original `open_database_connection` reference. |

If production approval is declined or expires, the command exits before opening a connection. Confirm the application and operation before asking again.

For development, a missing settings file or missing `APP_DATABASE_DIRECT_URL` exits with status 3 before the tool starts. Use the file `turnzero provision --origin https://dev.turnzero.ai` wrote, or provision again if the setting is missing. If the file cannot be read or a line has the wrong form, fix the file or the line the command names.

An invalid connection string also exits 3. Use the provisioned development value. Choose either `--environment development` or `--grant <id>`. The command exits 3 if it reads both or if another environment is named.

## Related

- [Bring an existing application](/cloud/guides/bring-an-existing-application/#3-carry-existing-records-into-the-database) explains import choices.
- [Add a database](/cloud/guides/add-a-database/) covers provisioning, development access and read-only queries.
- [The turnzero command reference](/cloud/reference/turnzero-command/) lists options and exit statuses.
