Skip to content
Home

处理分支

Learn how to develop and manage your Supabase branches

本指南讲解了如何高效使用 Supabase 分支,包括迁移管理、数据填充行为和开发工作流程。

🌐 This guide covers how to work with Supabase branches effectively, including migration management, seeding behavior, and development workflows.

订阅通知 #

🌐 Subscribing to notifications

当一个操作在持久分支上执行完成时,你可以订阅 webhook 通知。负载格式遵循 webhook 标准。

🌐 You can subscribe to webhook notifications when an action run completes on a persistent branch. The payload format follows the webhook standards.

{
"type": "run.completed",
"timestamp": "2025-10-17T02:27:18.705861793Z",
"data": {
"project_ref": "xuqpsshjxdecrwdyuxvs",
"details_url": "https://supabase.nodejs.cn/dashboard/project/xuqpsshjxdecrwdyuxvs/branches",
"action_run": {
"id": "d5f8b4298d0a4d37b99e255c7837e7af",
"created_at": "2025-10-17T02:27:10.133329324Z",
"steps": [
{
"name": "clone",
"status": "exited",
"updated_at": "2025-10-17T02:27:10.788435466Z"
},
{
"name": "pull",
"status": "exited",
"updated_at": "2025-10-17T02:27:11.701742857Z"
},
{
"name": "health",
"status": "exited",
"updated_at": "2025-10-17T02:27:12.79205717Z"
},
{
"name": "configure",
"status": "exited",
"updated_at": "2025-10-17T02:27:13.726839657Z"
},
{
"name": "migrate",
"status": "exited",
"updated_at": "2025-10-17T02:27:14.97017507Z"
},
{
"name": "seed",
"status": "exited",
"updated_at": "2025-10-17T02:27:15.637684921Z"
},
{
"name": "deploy",
"status": "exited",
"updated_at": "2025-10-17T02:27:18.604193114Z"
}
]
}
}
}

我们建议注册一个单一的 webhooks 处理器,根据负载类型将事件分发到下游服务。最简单的方法是部署一个 Edge Function。例如,下面的 Edge Function 会监听运行完成事件,以通知 Slack 通道。

🌐 We recommend registering a single webhooks processor that dispatches events to downstream services based on the payload type. The easiest way to do that is by deploying an Edge Function. For example, the following Edge Function listens for run completed events to notify a Slack channel.

supabase/functions/notify-slack/index.ts
// Setup type definitions for built-in Supabase Runtime APIs
import 'jsr:@supabase/functions-js/edge-runtime.d.ts'
console.log('Branching notification booted!')
const slack = Deno.env.get('SLACK_WEBHOOK_URL') ?? ''
Deno.serve(async (request) => {
const body = await request.json()
const blocks = [
{
type: 'header',
text: {
type: 'plain_text',
text: `Action run ${body.data.action_run.failure ? 'failed' : 'completed'}`,
emoji: true,
},
},
{
type: 'section',
fields: [
{
type: 'mrkdwn',
text: `*Branch ref:*\n${body.data.project_ref}`,
},
{
type: 'mrkdwn',
text: `*Run ID:*\n${body.data.action_run.id}`,
},
],
},
{
type: 'section',
fields: [
{
type: 'mrkdwn',
text: `*Started at:*\n${body.data.action_run.created_at}`,
},
{
type: 'mrkdwn',
text: `*Completed at:*\n${body.timestamp}`,
},
],
},
{
type: 'section',
text: {
type: 'mrkdwn',
text: `<${body.data.details_url}|View logs>`,
},
},
]
const resp = await fetch(slack, {
method: 'POST',
body: JSON.stringify({
blocks,
}),
})
const message = await resp.text()
return new Response(
JSON.stringify({
message,
}),
{
status: 200,
}
)
})
1
Setup Slack webhook URL

创建一个 Slack webhook URL 并将其设置为函数密钥。

supabase secrets set --project-ref <branch-ref> SLACK_WEBHOOK_URL=<your-webhook-url>
2
Deploy your webhooks processor

创建并部署一个边缘函数来处理 webhooks。

supabase functions deploy --project-ref <branch-ref> --use-api notify-slack
3
Update branch notification URL

把目标分支的通知 URL 更新为指向你的 Edge Function。

supabase branches update <branch-ref> --notify-url https://<branch-ref>.supabase.co/functions/v1/notify-slack

完成以上步骤后,每当目标分支上的操作运行完成时,你应该会收到一条 Slack 消息。

🌐 After completing the steps above, you should receive a Slack message whenever an action run completes on your target branch.

迁移和播种行为 #

🌐 Migration and seeding behavior

迁移是按顺序进行的。每次迁移都是在上一次的基础上进行的。

🌐 Migrations are run in sequential order. Each migration builds upon the previous one.

预览分支继承了你基础项目的迁移历史,所以它只会应用那些还没运行过的迁移。这在回滚迁移时可能会产生问题。

🌐 The preview branch inherits the migration history of your base project, so it only applies migrations that haven't been run yet. This can create an issue when rolling back migrations.

分支的默认权限 #

🌐 Default privileges on branches

新分支默认是安全的。无论基础项目的设置如何,它们在 public 架构上创建时都没有默认权限。分支上的新表、函数和序列在 anon、authenticated 或 service_role 通过数据 API 访问之前,需要明确授予权限。

🌐 New branches are secure by default. They are created without default privileges on the public schema, regardless of the setting on your base project. New tables, functions, and sequences on a branch require explicit grants before anon, authenticated, or service_role can reach them through the Data API.

你的迁移控制了一个分支是否重新启用这些权限。如果你的基础项目已启用默认权限,并且你的迁移历史是由 Supabase 分支或 Supabase CLI 初始化的,那么初始迁移已经包含授予 public 访问权限的 alter default privileges 语句。在新分支上运行它会恢复你的基础项目拥有的相同访问权限,所以不需要做任何更改。

🌐 Your migrations control whether a branch re-enables these privileges. If your base project has default privileges enabled and your migration history was initialized by Supabase Branching or the Supabase CLI, the initial migration already contains the alter default privileges statements that grant access on public. Running it on a new branch restores the same access your base project has, so no changes are needed.

有两种情况需要人工干预:

🌐 Two cases require manual intervention:

保持默认权限启用 #

🌐 Keep default privileges enabled

如果你的迁移历史不是由 Supabase 分支或 Supabase CLI 初始化的,你的初始迁移不会授予默认权限,所以新分支启动时不会有这些权限。要恢复与基础项目相同的访问权限:

🌐 If your migration history was not initialized by Supabase Branching or the Supabase CLI, your initial migration doesn't grant default privileges, so new branches start without them. To restore the same access your base project has:

1
Turn on default privileges on your base project

在 Supabase 控制面板中打开 数据 API 设置,然后开启 新实体的默认权限。

2
Add grants to your initial migration

在你的初始迁移文件开头插入以下语句。后续的迁移将继承这些权限,因此最终的数据库状态不会改变。

alter default privileges for role postgres in schema public grant usage, select, update on sequences to anon, authenticated, service_role;
alter default privileges for role postgres in schema public grant execute on functions to anon, authenticated, service_role;
alter default privileges for role postgres in schema public grant select, insert, update, delete on tables to anon, authenticated, service_role;
3
Repair the migration history of your base project

将更新后的迁移标记为已应用,这样它就不会在你的基础项目中再次运行。请参阅 诊断和修复同步错误。

supabase migration repair --status applied <migration-timestamp>

撤销默认权限 #

🌐 Revoke default privileges

为了提高安全性,我们建议不要在你的基础项目上自动暴露 public 模式。如果你的初始迁移是由 Supabase 分支或 Supabase CLI 生成的,它在分支上运行时会重新授予默认权限。要在你的基础项目和分支上撤销这些权限:

🌐 For improved security, we recommend not exposing the public schema automatically on your base project either. If your initial migration was generated by Supabase Branching or the Supabase CLI, it re-grants default privileges when it runs on a branch. To revoke them on your base project and branches:

1
Turn off default privileges on your base project

在 Supabase 控制面板中打开 数据 API 设置,然后关闭 新实体的默认权限。

2
Add a new migration that revokes the grants

使用 Supabase CLI 创建一个新的迁移文件。不要编辑初始迁移,因为那会影响你历史中的后续迁移。

supabase migration new revoke_default_privileges

把以下语句添加到生成的文件中:

alter default privileges for role postgres in schema public revoke select, insert, update, delete on tables from anon, authenticated, service_role;
alter default privileges for role postgres in schema public revoke execute on functions from anon, authenticated, service_role, public;
alter default privileges for role postgres in schema public revoke usage, select, update on sequences from anon, authenticated, service_role;
3
Commit and push

提交新的迁移文件并将其推送到你的 Git 仓库。迁移在合并时会在你的基础项目上运行,并且在每个新分支上也会运行,所以两个分支开始时都没有默认权限。

使用 ORM 或自定义种子脚本 #

🌐 Using ORM or custom seed scripts

如果你想使用自己的 ORM 来管理迁移和种子脚本,你需要在预览分支准备好之后在 GitHub Actions 中运行它们。可以使用以下示例 GHA 工作流来获取分支凭证。

🌐 If you want to use your own ORM for managing migrations and seed scripts, you will need to run them in GitHub Actions after the preview branch is ready. The branch credentials can be fetched using the following example GHA workflow.

.github/workflows/custom-orm.yaml
name: Custom ORM
on:
pull_request:
types:
- opened
- reopened
- synchronize
branches:
- main
paths:
- 'supabase/**'
jobs:
wait:
runs-on: ubuntu-latest
outputs:
status: ${{ steps.check.outputs.conclusion }}
steps:
- uses: fountainhead/action-wait-for-check@v1.2.0
id: check
with:
checkName: Supabase Preview
ref: ${{ github.event.pull_request.head.sha || github.sha }}
token: ${{ secrets.GITHUB_TOKEN }}
migrate:
needs:
- wait
if: ${{ needs.wait.outputs.status == 'success' }}
runs-on: ubuntu-latest
env:
SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}
SUPABASE_PROJECT_ID: ${{ secrets.SUPABASE_PROJECT_ID }}
steps:
- uses: supabase/setup-cli@v1
with:
version: latest
- run: supabase --experimental branches get "$GITHUB_HEAD_REF" -o env >> $GITHUB_ENV
- name: Custom ORM migration
run: psql "$POSTGRES_URL_NON_POOLING" -c 'select 1'

回滚迁移 #

🌐 Rolling back migrations

你可能想回滚之前迁移中所做的更改。例如,你可能已经推送了一个包含你不再需要的模式更改的迁移文件。

🌐 You might want to roll back changes you've made in an earlier migration change. For example, you may have pushed a migration file containing schema changes you no longer want.

要解决这个问题,先推送最新的更改,然后在 Supabase 中删除预览分支,再重新打开它。

🌐 To fix this, push the latest changes, then delete the preview branch in Supabase and reopen it.

新的预览分支是你基础项目的全新克隆,默认会从 ./supabase/seed.sql 文件重新生成。旧预览分支上的任何额外数据更改都会丢失。

🌐 The new preview branch is a fresh clone of your base project and is reseeded from the ./supabase/seed.sql file by default. Any additional data changes made on the old preview branch are lost.

如果你想重新运行基础项目已经应用的迁移,请改为从 Supabase 控制面板重置分支。重置会按顺序重新运行所有迁移,并清除分支上现有的数据。

🌐 To rerun migrations that your base project has already applied, reset the branch from the Supabase dashboard instead. A reset reruns all migrations in sequential order and drops existing data on the branch.

种子行为 #

🌐 Seeding behavior

你的预览分支已使用与本地播种行为相同的示例数据进行初始化。

🌐 Your Preview Branches are seeded with sample data using the same as local seeding behavior.

数据库只会在创建预览分支时初始化一次。要重新执行初始化,只需删除预览分支,然后通过关闭并重新打开你的 Pull Request 来重新创建它。

🌐 The database is only seeded once, when the preview branch is created. To rerun seeding, delete the preview branch and recreate it by closing, and reopening your pull request.

使用分支进行开发 #

🌐 Developing with branches

你可以使用本地或远程开发流程来用分支进行开发。

🌐 You can develop with branches using either local or remote development workflows.

本地开发工作流程 #

🌐 Local development workflow

  1. 为你的功能创建一个新的 Git 分支
  2. 使用 Supabase CLI 进行模式更改
  3. 使用 supabase db diff 生成迁移文件
  4. 在本地测试你的更改
  5. 提交并推送到 GitHub
  6. 创建一个拉取请求来生成预览分支

如果你的项目使用声明式模式,请在 supabase/schemas/ 中编辑你的文件,并使用 supabase db schema declarative sync 生成迁移,而不是 supabase db diff,因为在 pg-delta 上它从不将你的模式文件作为基线。如果你的项目还没有启用 pg-delta,请改为参考传统 migra 引擎上的声明式模式。分支操作只适用于已提交的迁移文件,所以请将模式文件和生成的迁移文件一起提交。

🌐 If your project uses declarative schemas, edit your files in supabase/schemas/ and generate migrations with supabase db schema declarative sync instead of supabase db diff, which on pg-delta never uses your schema files as its baseline. If your project hasn't enabled pg-delta, follow Declarative schemas on the legacy migra engine instead. Branching applies only committed migration files, so commit the schema files and the generated migrations together.

远程开发工作流程 #

🌐 Remote development workflow

  1. 在 Supabase 仪表板里创建一个预览分支
  2. 使用分支下拉菜单切换分支
  3. 在仪表板中进行模式更改
  4. 使用 supabase db pull 在本地拉取更改
  5. 提交生成的迁移文件
  6. 推送到你的 Git 仓库

管理分支环境 #

🌐 Managing branch environments

在分支之间切换 #

🌐 Switching between branches

在 Supabase 仪表板中使用分支下拉菜单在不同分支之间切换。每个分支都有自己的:

🌐 Use the branch dropdown in the Supabase dashboard to switch between different branches. Each branch has its own:

  • 数据库实例
  • API端点
  • 身份验证设置
  • 存储桶

正在访问分支凭证 #

🌐 Accessing branch credentials

每个分支都有独特的凭证,你可以在仪表板上找到:

🌐 Each branch has unique credentials that you can find in the dashboard:

  1. 切换到你想要的分支
  2. 导航到 设置 > API
  3. 复制分支专用的 URL 和密钥

分支隔离 #

🌐 Branch isolation

各个分支是完全隔离的。在一个分支上做的修改不会影响其他分支,包括:

🌐 Branches are completely isolated from each other. Changes made in one branch don't affect others, including:

  • 数据库模式和数据
  • 存储对象
  • 边缘函数
  • 认证配置

下一步 #

🌐 Next steps