Databases

Branch a database

Copy a database and check that changes stay on the branch

Branch orders as orders-staging to work on a copy of its data without touching the source.

You need psql and the editor or admin role in your workspace. The examples use the CLI. Over MCP, an agent does the same with branch_database. Use orders from Create and connect to a database. Keep the name orders-staging free.

Prepare the source

nevia pg status orders

You can branch a ready or sleeping database with no pending transition or running operation. The SQL example needs ready, so wake orders first if it is sleeping. Copying data needs a persistent disk, which the deployment supplies.

Use a small table to check the copy. If you already have pings from Create your first database, this adds one row:

psql "$(nevia pg connect orders --uri)" <<'SQL'
CREATE TABLE IF NOT EXISTS pings (id serial PRIMARY KEY, note text);
INSERT INTO pings (note) VALUES ('baseline-a');
SELECT count(*) FROM pings;
SQL

Note the row count. A new table has one row. Leave the table alone on the source until you finish checking the branch.

Branch

Commit the writes you need, then wait at least five seconds. A running source can reuse a disk snapshot less than five seconds old, and the branch would miss newer writes:

sleep 5
nevia pg branch orders -b orders-staging --wait
nevia pg status orders-staging

The branch should be ready, with no pending transition and parent set to the ID of orders. It has its own host and data disks, and inherits the source's Postgres version, size and storage. The branch has its own password and lands in the source's project. The source keeps running, and a fresh snapshot briefly freezes its disk writes.

With --wait, branch creation reads and prints the branch's connection. If the branch is ready but that read fails, the CLI prints the branch and the separate error, then exits with the read error's status. Retrieve the connection with nevia pg connect orders-staging before continuing. The branch already exists.

Use the branch's connection to check the copied data:

psql "$(nevia pg connect orders-staging --uri)" -c 'SELECT count(*) FROM pings;'

The count should match the source. The query also confirms the branch accepts TLS connections.

Check a change

Insert a row on the branch:

psql "$(nevia pg connect orders-staging --uri)" -c \
  "INSERT INTO pings (note) VALUES ('branch-mutation');"

Then count both:

for db in orders orders-staging; do
  psql "$(nevia pg connect "$db" --uri)" -c 'SELECT count(*) FROM pings;'
done

The source count is unchanged. The branch has one more row.

Clean up

Delete the branch and its data. If you enabled protection on it, clear that first:

nevia pg rm orders-staging --yes --wait

Deleting orders leaves its branches running with their own data. See Sleep, wake and delete a database, Database lifecycle states, and the nevia pg branch options.

On this page