# Workflow: database branch per PR preview

## Goal
Every pull request gets its own isolated database, seeded from production's current state, living exactly as long as the preview deployment.

## Steps
1. On PR open/synchronize, call the Neon API to create a branch from the production branch:
   `POST /projects/[project-id]/branches` with `parent_id` set to the prod branch and an endpoint of type `read_write`. Poll the returned operation until it reports finished.
2. Read the new branch's connection string from the API response (or the Console).
3. Run migrations against the new branch using the direct connection string.
4. Inject the branch connection string into the preview deployment's environment and deploy.
5. On PR close/merge, delete the branch: `DELETE /projects/[project-id]/branches/[branch-id]`, then tear down the preview deployment.

## Ordering constraints
- Branch must exist and its operation be finished before migrations run; migrations against a half-created branch fail confusingly.
- Delete the branch only after the preview deployment is gone, so no dying instance writes to a deleted database.
- Set branch expiration (1 day) as a backstop; the explicit delete on PR close is the primary path.

## Traps
- API-created branches never expire by default: the delete step is load-bearing, not optional.
- Preview branches each get a compute: size the default compute small and set project autoscaling defaults so previews do not each bill like prod.
- Never branch previews from a preview; always from the production (or staging) branch, or previews drift from reality.

## Verify
Open a PR: branch appears, preview works against isolated data. Close it: branch and data are gone within the pipeline run.