pocketbase

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

PocketBase Skill

PocketBase 技能文档

Skill for operating a PocketBase v0.23+ backend via REST API and as a Go package. Uses Python scripts (standard library only) to perform authentication, collection CRUD, record CRUD, backup, migration file generation, and includes design guidance for API rules, relations, and security patterns. Supports Go package mode with Go migrations, hooks, custom routes, and middleware.
本技能支持通过REST API或Go包模式操作v0.23+版本的PocketBase后端。仅使用Python标准库脚本即可完成认证、集合CRUD、记录CRUD、备份、迁移文件生成等操作,同时包含API规则、关联关系和安全模式的设计指导。还支持Go包模式,提供Go迁移、钩子、自定义路由和中间件功能。

Skill Resources

技能资源

All resources for this skill are bundled in the skill directory at ``:
  • Scripts:
    scripts/
    — Python scripts for API operations
  • References:
    references/
    — Detailed docs loaded on demand
  • Assets:
    assets/
    — Templates and static files
When you need to look up PocketBase details or find skill-related files, check this directory first — everything you need is already here. There is no need to search the user's home directory or other projects.
本技能的所有资源都打包在技能目录中:
  • 脚本
    scripts/
    — 用于API操作的Python脚本
  • 参考文档
    references/
    — 按需加载的详细文档
  • 资源文件
    assets/
    — 模板和静态文件
当你需要查询PocketBase细节或查找技能相关文件时,请先查看此目录——所需内容均已包含在内,无需搜索用户主目录或其他项目。

Mode Detection

模式检测

Determine the project mode:
  1. go.mod
    exists and contains
    github.com/pocketbase/pocketbase
    Go package mode
  2. Otherwise → Standalone mode (existing workflow)
Go package mode additional references:
  • Setup & structure →
    Read references/go-framework.md
  • Migrations →
    Read references/go-migrations.md
  • Hooks & custom routes →
    Read references/go-hooks-routes.md
Go package mode still uses the same REST API. Python scripts (
pb_collections.py
, etc.) and E2E tests work as-is.
判断项目模式:
  1. 存在
    go.mod
    且包含
    github.com/pocketbase/pocketbase
    Go包模式
  2. 否则 → 独立模式(现有工作流)
Go包模式额外参考文档:
  • 配置与结构 → 查看
    references/go-framework.md
  • 迁移 → 查看
    references/go-migrations.md
  • 钩子与自定义路由 → 查看
    references/go-hooks-routes.md
Go包模式仍可使用相同的REST API。Python脚本(如
pb_collections.py
等)和端到端测试可直接使用。

0. Design Workflow & Decision Making

0. 设计工作流与决策制定

Read
references/gotchas.md
FIRST
before writing any PocketBase code. Your training data contains outdated v0.22 patterns that will fail on v0.23+. Check field JSON: ensure properties are flat (no
options
wrapper) and collection key is
fields
(not
schema
).
在编写任何PocketBase代码前,请先阅读
references/gotchas.md
你的训练数据包含已过时的v0.22模式,这些模式在v0.23+版本中会失效。 检查字段JSON:确保属性为扁平结构(无
options
包装器),且集合使用
fields
键(而非
schema
)。

⚠️ v0.22 Anti-Patterns — DO NOT USE

⚠️ v0.22 反模式 — 请勿使用

Field properties must be FLAT —
options
wrapper was removed in v0.23+:
json
// WRONG (v0.22) — "options" wrapper does not exist in v0.23+
{"name": "status", "type": "select", "options": {"values": ["draft", "published"], "maxSelect": 1}}
{"name": "avatar", "type": "file", "options": {"maxSelect": 1, "maxSize": 5242880}}
{"name": "author", "type": "relation", "options": {"collectionId": "...", "maxSelect": 1}}

// CORRECT (v0.23+) — all properties are top-level (flat)
{"name": "status", "type": "select", "values": ["draft", "published"], "maxSelect": 1}
{"name": "avatar", "type": "file", "maxSelect": 1, "maxSize": 5242880}
{"name": "author", "type": "relation", "collectionId": "...", "maxSelect": 1}
Applies to ALL field types:
select
(values, maxSelect),
file
(maxSelect, maxSize, mimeTypes, thumbs),
relation
(collectionId, maxSelect),
text
(min, max, pattern).
This flat-property rule applies everywhere — inline JSON in
pb_collections.py create
,
collections.json
files used with
pb_collections.py import
, and Go migration code. If you see
"options": {
in any PocketBase field definition, it is WRONG.
Collection JSON: use
fields
key, not
schema
:
json
// WRONG: {"name": "posts", "type": "base", "schema": [...]}
// CORRECT: {"name": "posts", "type": "base", "fields": [...]}
Migration JS: use typed constructors, not
SchemaField
:
js
// WRONG:   collection.schema.addField(new SchemaField({type: "select", options: {values: ["a"]}}))
// CORRECT: collection.fields.add(new SelectField({name: "status", values: ["a"]}))
Pre-Generation Checklist — verify before writing any PocketBase code:
  • Field properties are flat (no
    options
    wrapper)
  • Collection JSON uses
    fields
    key (not
    schema
    )
  • Migrations use typed constructors (
    SelectField
    ,
    TextField
    ,
    RelationField
    , etc.)
  • Hooks use
    e.next()
    and
    $app.findRecordById()
    (not
    $app.dao()
    )
  • Routes use
    {paramName}
    syntax (not
    :paramName
    )
  • @collection
    references in API rules use
    ?=
    (not
    =
    ) —
    =
    breaks with 2+ rows
Go package mode additional checks:
  • Collections created via
    pb_collections.py
    (not hand-written migration files)
  • Auto-generated migration files in
    pb_migrations/
    are committed to git
  • migratecmd.MustRegister()
    with
    Automigrate: true
    (dev) is configured in
    main.go
  • _ "yourmodule/migrations"
    blank import exists in
    main.go
    (if manual migrations are used)
  • Manual migration files (seed data, data transforms) use
    package migrations
    +
    func init()
    +
    m.Register()
  • Rules set with
    types.Pointer("rule")
    (not direct string assignment —
    *string
    type)
  • Hooks call
    return e.Next()
    (omitting causes request hang)
字段属性必须为扁平结构 — v0.23+已移除
options
包装器:
json
// 错误写法(v0.22)—— v0.23+中不存在"options"包装器
{"name": "status", "type": "select", "options": {"values": ["draft", "published"], "maxSelect": 1}}
{"name": "avatar", "type": "file", "options": {"maxSelect": 1, "maxSize": 5242880}}
{"name": "author", "type": "relation", "options": {"collectionId": "...", "maxSelect": 1}}

// 正确写法(v0.23+)—— 所有属性均为顶层(扁平结构)
{"name": "status", "type": "select", "values": ["draft", "published"], "maxSelect": 1}
{"name": "avatar", "type": "file", "maxSelect": 1, "maxSize": 5242880}
{"name": "author", "type": "relation", "collectionId": "...", "maxSelect": 1}
此规则适用于所有字段类型:
select
(values、maxSelect)、
file
(maxSelect、maxSize、mimeTypes、thumbs)、
relation
(collectionId、maxSelect)、
text
(min、max、pattern)。
此扁平属性规则适用于所有场景 ——
pb_collections.py create
中的内联JSON、
pb_collections.py import
使用的
collections.json
文件,以及Go迁移代码。如果在任何PocketBase字段定义中看到
"options": {
,均为错误写法。
集合JSON:使用
fields
键,而非
schema
json
// 错误写法:{"name": "posts", "type": "base", "schema": [...]}
// 正确写法:{"name": "posts", "type": "base", "fields": [...]}
JS迁移:使用类型化构造函数,而非
SchemaField
js
// 错误写法:   collection.schema.addField(new SchemaField({type: "select", options: {values: ["a"]}}))
// 正确写法:   collection.fields.add(new SelectField({name: "status", values: ["a"]}))
预生成检查清单 —— 在编写任何PocketBase代码前验证:
  • 字段属性为扁平结构(无
    options
    包装器)
  • 集合JSON使用
    fields
    键(而非
    schema
  • 迁移使用类型化构造函数(
    SelectField
    TextField
    RelationField
    等)
  • 钩子使用
    e.next()
    $app.findRecordById()
    (而非
    $app.dao()
  • 路由使用
    {paramName}
    语法(而非
    :paramName
  • API规则中的
    @collection
    引用使用
    ?=
    (而非
    =
    )——
    =
    在2行以上数据时会失效
Go包模式额外检查项:
  • 通过
    pb_collections.py
    创建集合(而非手动编写迁移文件)
  • pb_migrations/
    中自动生成的迁移文件已提交至git
  • main.go
    中配置了
    migratecmd.MustRegister()
    并设置
    Automigrate: true
    (开发环境)
  • 如果使用手动迁移,
    main.go
    中存在
    _ "yourmodule/migrations"
    空白导入
  • 手动迁移文件(种子数据、数据转换)使用
    package migrations
    +
    func init()
    +
    m.Register()
  • 使用
    types.Pointer("rule")
    设置规则(而非直接字符串赋值——类型为
    *string
  • 钩子调用
    return e.Next()
    (省略会导致请求挂起)

Bootstrap (First-Time Setup)

初始化(首次设置)

When PocketBase is not yet running:
  1. Download — Get the latest version:
    bash
    VERSION=$(curl -s https://api.github.com/repos/pocketbase/pocketbase/releases/latest | python3 -c "import sys,json; print(json.load(sys.stdin)['tag_name'].lstrip('v'))")
    ARCH=$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')
    OS=$(uname -s | tr A-Z a-z)
    curl -sL "https://github.com/pocketbase/pocketbase/releases/download/v${VERSION}/pocketbase_${VERSION}_${OS}_${ARCH}.zip" -o pb.zip && unzip -o pb.zip pocketbase && rm pb.zip
  2. Create superuser
    ./pocketbase superuser create admin@example.com <password>
  3. Write
    .env
    — Confirm credentials with user, write
    .env
    , add to
    .gitignore
  4. Start
    nohup ./pocketbase serve --http=127.0.0.1:8090 > pb.log 2>&1 &
  5. Verify
    python scripts/pb_health.py
当PocketBase尚未运行时:
  1. 下载 — 获取最新版本:
    bash
    VERSION=$(curl -s https://api.github.com/repos/pocketbase/pocketbase/releases/latest | python3 -c "import sys,json; print(json.load(sys.stdin)['tag_name'].lstrip('v'))")
    ARCH=$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/')
    OS=$(uname -s | tr A-Z a-z)
    curl -sL "https://github.com/pocketbase/pocketbase/releases/download/v${VERSION}/pocketbase_${VERSION}_${OS}_${ARCH}.zip" -o pb.zip && unzip -o pb.zip pocketbase && rm pb.zip
  2. 创建超级用户
    ./pocketbase superuser create admin@example.com <password>
  3. 编写
    .env
    文件
    — 与用户确认凭据,编写
    .env
    并添加至
    .gitignore
  4. 启动
    nohup ./pocketbase serve --http=127.0.0.1:8090 > pb.log 2>&1 &
  5. 验证
    python scripts/pb_health.py

Design Decision Tree

设计决策流程

When building a PocketBase application, follow this sequence:
  1. Requirements — Identify entities, relationships, and access patterns
  2. Collection types — Choose
    base
    ,
    auth
    , or
    view
    for each entity
  3. Fields — Design fields per collection (
    Read references/field-types.md
    )
  4. Relations — Design relations (
    Read references/relation-patterns.md
    )
  5. API rules — Set security rules (
    Read references/api-rules-guide.md
    )
    • Default to
      null
      (deny all). Open only what is needed.
    • null
      = superuser only,
      ""
      = anyone including guests
  6. Create — Create collections via Python scripts (both modes)
    • Use
      pb_collections.py create
      or
      pb_collections.py import --file collections.json
    • PocketBase auto-generates migration files (
      .js
      in standalone,
      .go
      in Go package mode with
      Automigrate: true
      )
    • Commit the auto-generated migration files to git
    • Do NOT hand-write migration files for collection schema creation — let PocketBase generate them
    • For data transforms, seed data, or raw SQL, see Section 6 (Migrations)
    • Hooks/routes: Standalone uses JSVM (
      pb_hooks/*.pb.js
      ), Go uses Go code —
      Read references/go-hooks-routes.md
  7. Seed data — Insert sample records for verification
  8. Test — Use Python E2E tests for all integration testing:
    • Read
      references/e2e-testing.md
    • Use
      pb_e2e_helpers
      module
    • Test positive AND negative access for each collection's API rules
    • Also use E2E tests for custom routes and hooks (Go or JSVM) — call the HTTP endpoint and verify the response
    • Pure functions (utilities, validation, transformation logic) that do not depend on PocketBase can use standard
      go test
  9. Verify — Run self-tests (see below)
构建PocketBase应用时,请遵循以下步骤:
  1. 需求分析 — 确定实体、关联关系和访问模式
  2. 集合类型选择 — 为每个实体选择
    base
    auth
    view
    类型
  3. 字段设计 — 为每个集合设计字段(查看
    references/field-types.md
  4. 关联关系设计 — 设计关联关系(查看
    references/relation-patterns.md
  5. API规则设置 — 配置安全规则(查看
    references/api-rules-guide.md
    • 默认设置为
      null
      (拒绝所有访问)。仅开放必要权限。
    • null
      = 仅超级用户可访问,
      ""
      = 任何人(包括访客)均可访问
  6. 创建集合 — 通过Python脚本创建集合(两种模式均适用)
    • 使用
      pb_collections.py create
      pb_collections.py import --file collections.json
    • PocketBase会自动生成迁移文件(独立模式下为
      .js
      ,Go包模式且
      Automigrate: true
      时为
      .go
    • 将自动生成的迁移文件提交至git
    • 请勿手动编写集合架构创建的迁移文件 — 让PocketBase自动生成
    • 数据转换、种子数据或原始SQL操作,请查看第6节(迁移)
    • 钩子/路由:独立模式使用JSVM(
      pb_hooks/*.pb.js
      ),Go模式使用Go代码 — 查看
      references/go-hooks-routes.md
  7. 种子数据插入 — 插入示例记录用于验证
  8. 测试 — 使用Python端到端测试进行所有集成测试:
    • 查看
      references/e2e-testing.md
    • 使用
      pb_e2e_helpers
      模块
    • 测试每个集合API规则的正向和负向访问
    • 自定义路由和钩子(Go或JSVM)也需进行端到端测试 — 调用HTTP端点并验证响应
    • 不依赖PocketBase的纯函数(工具、验证、转换逻辑)可使用标准
      go test
  9. 验证 — 运行自测试(见下文)

Self-Test Verification

自测试验证

After creating or modifying collections:
  1. Confirm schema:
    pb_collections.py get <name>
  2. CRUD smoke test: create → list → get → update → delete
  3. Rule verification: test as non-superuser
    • Use
      pb_auth.py --collection users --identity ... --password ...
    • Verify denied access returns expected behavior
  4. E2E test — Required when any collection has a non-
    null
    API rule, or when custom routes/hooks exist:
    • Read references/e2e-testing.md
    • Generate a test script (
      test_e2e.py
      ) in the project root using
      pb_e2e_helpers
      module
    • The test MUST cover:
      • Unauthenticated access is denied (expect 401/403)
      • Authenticated user can perform allowed operations
      • User cannot access another user's resources (cross-user isolation)
      • Spoofing prevention — if
        createRule
        contains
        @request.body.X = @request.auth.id
        , verify that setting X to a different user's ID is rejected
      • cascadeDelete
        behavior — deleting a parent removes related child records
      • null
        rule (superuser-only) endpoints return 403 for regular users
      • Custom routes: correct response for valid requests, auth middleware rejects unauthenticated/unauthorized requests
      • Hook side effects: verify the expected DB state or response after the hook fires
    • Run the test and fix any failures before marking the task complete
创建或修改集合后:
  1. 确认架构:
    pb_collections.py get <name>
  2. CRUD冒烟测试:创建 → 列表 → 获取 → 更新 → 删除
  3. 规则验证:以非超级用户身份测试
    • 使用
      pb_auth.py --collection users --identity ... --password ...
    • 验证被拒绝的访问是否返回预期行为
  4. 端到端测试 — 当任何集合的API规则非
    null
    ,或存在自定义路由/钩子时必须执行:
    • 查看
      references/e2e-testing.md
    • 使用
      pb_e2e_helpers
      模块在项目根目录生成测试脚本(
      test_e2e.py
    • 测试必须覆盖:
      • 未认证访问被拒绝(预期返回401/403)
      • 已认证用户可执行允许的操作
      • 用户无法访问其他用户的资源(跨用户隔离)
      • 防伪造 — 如果
        createRule
        包含
        @request.body.X = @request.auth.id
        ,验证将X设置为其他用户ID会被拒绝
      • cascadeDelete
        行为 — 删除父记录会移除相关子记录
      • null
        规则(仅超级用户可访问)的端点对普通用户返回403
      • 自定义路由:有效请求返回正确响应,认证中间件拒绝未认证/未授权请求
      • 钩子副作用:验证钩子触发后的预期数据库状态或响应
    • 运行测试并修复所有失败项后,方可标记任务完成

Reference Index

参考文档索引

TopicReference
Gotchas & pitfalls
Read references/gotchas.md
API rules design
Read references/api-rules-guide.md
Relation patterns
Read references/relation-patterns.md
JS SDK (frontend)
Read references/js-sdk.md
JSVM hooks (server)
Read references/jsvm-hooks.md
File handling
Read references/file-handling.md
E2E testing patterns
Read references/e2e-testing.md
Go framework setup
Read references/go-framework.md
Go migrations
Read references/go-migrations.md
Go hooks & routes
Read references/go-hooks-routes.md
Production deployment (Docker, binary, proxy)
Read references/deployment.md
in the
pb-react-spa
skill
React SPA frontend
pb-react-spa
skill (separate skill)
主题参考文档
常见陷阱
查看 references/gotchas.md
API规则设计
查看 references/api-rules-guide.md
关联关系模式
查看 references/relation-patterns.md
JS SDK(前端)
查看 references/js-sdk.md
JSVM钩子(服务端)
查看 references/jsvm-hooks.md
文件处理
查看 references/file-handling.md
端到端测试模式
查看 references/e2e-testing.md
Go框架配置
查看 references/go-framework.md
Go迁移
查看 references/go-migrations.md
Go钩子与路由
查看 references/go-hooks-routes.md
生产部署(Docker、二进制、代理)
查看 pb-react-spa 技能中的 references/deployment.md
React SPA前端
pb-react-spa
技能(独立技能)

1. Prerequisites and Configuration

1. 前置条件与配置

Getting and Starting PocketBase

获取并启动PocketBase

If PocketBase is not yet installed, guide the user to download the latest version:
Check the latest version:
bash
curl -s https://api.github.com/repos/pocketbase/pocketbase/releases/latest | python3 -c "import sys,json; print(json.load(sys.stdin)['tag_name'])"
Download URL pattern:
https://github.com/pocketbase/pocketbase/releases/download/v{VERSION}/pocketbase_{VERSION}_{OS}_{ARCH}.zip
Platform asset names:
PlatformAsset name
Linux amd64
pocketbase_{VERSION}_linux_amd64.zip
Linux arm64
pocketbase_{VERSION}_linux_arm64.zip
macOS amd64
pocketbase_{VERSION}_darwin_amd64.zip
macOS arm64 (Apple Silicon)
pocketbase_{VERSION}_darwin_arm64.zip
Windows amd64
pocketbase_{VERSION}_windows_amd64.zip
Download, extract, and start:
bash
undefined
如果尚未安装PocketBase,引导用户下载最新版本:
检查最新版本:
bash
curl -s https://api.github.com/repos/pocketbase/pocketbase/releases/latest | python3 -c "import sys,json; print(json.load(sys.stdin)['tag_name'])"
下载URL格式:
https://github.com/pocketbase/pocketbase/releases/download/v{VERSION}/pocketbase_{VERSION}_{OS}_{ARCH}.zip
平台资源名称:
平台资源名称
Linux amd64
pocketbase_{VERSION}_linux_amd64.zip
Linux arm64
pocketbase_{VERSION}_linux_arm64.zip
macOS amd64
pocketbase_{VERSION}_darwin_amd64.zip
macOS arm64(Apple Silicon)
pocketbase_{VERSION}_darwin_arm64.zip
Windows amd64
pocketbase_{VERSION}_windows_amd64.zip
下载、解压并启动:
bash
undefined

Example for Linux amd64 (replace VERSION with the actual version number, e.g. 0.28.0)

Linux amd64示例(将VERSION替换为实际版本号,如0.28.0)

VERSION=0.28.0 curl -L -o pocketbase.zip "https://github.com/pocketbase/pocketbase/releases/download/v${VERSION}/pocketbase_${VERSION}_linux_amd64.zip" unzip pocketbase.zip ./pocketbase serve

**Create a superuser:**
```bash
./pocketbase superuser create admin@example.com yourpassword
Starting PocketBase in background (for Claude Code sessions):
bash
undefined
VERSION=0.28.0 curl -L -o pocketbase.zip "https://github.com/pocketbase/pocketbase/releases/download/v${VERSION}/pocketbase_${VERSION}_linux_amd64.zip" unzip pocketbase.zip ./pocketbase serve

**创建超级用户:**
```bash
./pocketbase superuser create admin@example.com yourpassword
在Claude Code会话中后台启动PocketBase:
bash
undefined

Start with nohup (survives shell exit)

使用nohup启动(可在shell退出后继续运行)

nohup ./pocketbase serve --http=127.0.0.1:8090 > pb.log 2>&1 & echo "PID: $!"
nohup ./pocketbase serve --http=127.0.0.1:8090 > pb.log 2>&1 & echo "PID: $!"

Check if running

检查是否运行

python scripts/pb_health.py
python scripts/pb_health.py

Stop

停止服务

kill $(pgrep -f 'pocketbase serve')

> **Important:** Do NOT use Bash tool's `&` alone — the process dies when the shell session ends. Always use `nohup`.

> **Agent instruction:** If the user's PocketBase is not running or not installed, always recommend downloading the latest version using the GitHub API one-liner above to determine the current version number.
kill $(pgrep -f 'pocketbase serve')

> **重要提示:** 请勿仅使用Bash工具的`&` — 进程会在shell会话结束时终止。请始终使用`nohup`。

> **Agent指令:** 如果用户的PocketBase未运行或未安装,始终建议使用上述GitHub API单行命令确定当前版本号,然后下载最新版本。

Environment Variables

环境变量

VariableRequiredDefaultDescription
PB_URL
No
http://127.0.0.1:8090
PocketBase base URL
PB_SUPERUSER_EMAIL
Yes*Superuser email address
PB_SUPERUSER_PASSWORD
Yes*Superuser password
*Required when performing superuser operations.
If environment variables are not set, the
.env
file will be loaded from the current working directory. If not found there, parent directories are searched up to the filesystem root (useful for monorepo setups where scripts may run from a subdirectory).
env
PB_URL=http://127.0.0.1:8090
PB_SUPERUSER_EMAIL=admin@example.com
PB_SUPERUSER_PASSWORD=your-password
Important: If environment variables are not set, confirm the values with the user before executing operations. When writing credentials to a
.env
file, ensure that
.env
is included in
.gitignore
.
变量是否必填默认值描述
PB_URL
http://127.0.0.1:8090
PocketBase基础URL
PB_SUPERUSER_EMAIL
是*超级用户邮箱地址
PB_SUPERUSER_PASSWORD
是*超级用户密码
*执行超级用户操作时必填。
如果未设置环境变量,将从当前工作目录加载
.env
文件。如果未找到,将向上搜索父目录直至文件系统根目录(适用于单体仓库设置,脚本可能从子目录运行)。
env
PB_URL=http://127.0.0.1:8090
PB_SUPERUSER_EMAIL=admin@example.com
PB_SUPERUSER_PASSWORD=your-password
重要提示: 如果未设置环境变量,执行操作前请与用户确认值。将凭据写入
.env
文件时,确保
.env
已添加至
.gitignore

pb_config.py
Exports

pb_config.py
导出项

All PB scripts share this module. Available exports:
ExportTypeDescription
PB_URL
str
PocketBase base URL (from env or default
http://127.0.0.1:8090
)
PB_SUPERUSER_EMAIL
str
Superuser email (from env)
PB_SUPERUSER_PASSWORD
str
Superuser password (from env)
pb_request(method, path, data, token, raw_response)
functionLow-level HTTP request to PB API
pb_authed_request(method, path, data, raw_response)
functionAuto-authenticated superuser request (retries on 401)
get_superuser_token(force)
functionGet cached superuser bearer token
print_result(success, status, data)
functionPrint structured JSON output
PBRequestError
exceptionRaised on HTTP errors (has
.status
and
.data
)
Do not invent exports that don't exist (e.g.,
get_config
). Check this table or read
pb_config.py
directly.
所有PB脚本共享此模块。可用导出项:
导出项类型描述
PB_URL
str
PocketBase基础URL(来自环境变量或默认值
http://127.0.0.1:8090
PB_SUPERUSER_EMAIL
str
超级用户邮箱(来自环境变量)
PB_SUPERUSER_PASSWORD
str
超级用户密码(来自环境变量)
pb_request(method, path, data, token, raw_response)
函数向PB API发送底层HTTP请求
pb_authed_request(method, path, data, raw_response)
函数自动认证的超级用户请求(401时重试)
get_superuser_token(force)
函数获取缓存的超级用户Bearer令牌
print_result(success, status, data)
函数打印结构化JSON输出
PBRequestError
异常HTTP错误时抛出(包含
.status
.data
请勿虚构不存在的导出项(如
get_config
)。请查看此表格或直接阅读
pb_config.py

Connection Check

连接检查

bash
python scripts/pb_health.py
Runs a health check and (if credentials are available) a superuser authentication test.
bash
python scripts/pb_health.py
运行健康检查,并(如果凭据可用)执行超级用户认证测试。

2. Authentication

2. 认证

Superuser Authentication

超级用户认证

bash
python scripts/pb_auth.py
Authenticates using
PB_SUPERUSER_EMAIL
and
PB_SUPERUSER_PASSWORD
via
POST /api/collections/_superusers/auth-with-password
. Returns a token.
bash
python scripts/pb_auth.py
通过
POST /api/collections/_superusers/auth-with-password
使用
PB_SUPERUSER_EMAIL
PB_SUPERUSER_PASSWORD
进行认证,返回令牌。

User Authentication

用户认证

bash
python scripts/pb_auth.py --collection users --identity user@example.com --password secret
Authenticates against any auth collection.
bash
python scripts/pb_auth.py --collection users --identity user@example.com --password secret
针对任何认证集合进行认证。

Token Usage

令牌使用

Each script internally auto-acquires and caches the superuser token. On a 401 error, it retries authentication once.
Details:
Read references/auth-api.md
— OAuth2, impersonate, password reset, etc.
每个脚本内部会自动获取并缓存超级用户令牌。遇到401错误时,会重新认证一次。
详细信息: 查看
references/auth-api.md
— OAuth2、模拟、密码重置等。

3. Collection Management

3. 集合管理

List

列出集合

bash
python scripts/pb_collections.py list
python scripts/pb_collections.py list --filter "name~'user'" --sort "-created"
bash
python scripts/pb_collections.py list
python scripts/pb_collections.py list --filter "name~'user'" --sort "-created"

Get

获取集合

bash
python scripts/pb_collections.py get posts
python scripts/pb_collections.py get pbc_1234567890
bash
python scripts/pb_collections.py get posts
python scripts/pb_collections.py get pbc_1234567890

Create

创建集合

bash
undefined
bash
undefined

Inline JSON

内联JSON

python scripts/pb_collections.py create '{"name":"posts","type":"base","fields":[{"name":"title","type":"text","required":true},{"name":"content","type":"editor"}]}'
python scripts/pb_collections.py create '{"name":"posts","type":"base","fields":[{"name":"title","type":"text","required":true},{"name":"content","type":"editor"}]}'

From file

从文件读取

python scripts/pb_collections.py create --file schema.json

Collection types:
- `base` — Standard data collection
- `auth` — Auth collection (automatically adds email, password, username, etc.)
- `view` — Read-only SQL view (requires `viewQuery`)

> **Warning:** PocketBase ships with a `users` auth collection already created. Do **not** `POST` to create a new `users` collection — it will fail with a name conflict. Instead, use `PATCH /api/collections/users` (or `pb_collections.py update users '{...}'`) to customize the existing collection (add fields, change rules, etc.).
python scripts/pb_collections.py create --file schema.json

集合类型:
- `base` — 标准数据集合
- `auth` — 认证集合(自动添加邮箱、密码、用户名等字段)
- `view` — 只读SQL视图(需要`viewQuery`)

> **警告:** PocketBase默认已创建`users`认证集合。请勿`POST`创建新的`users`集合 — 会因名称冲突失败。请使用`PATCH /api/collections/users`(或`pb_collections.py update users '{...}'`)自定义现有集合(添加字段、修改规则等)。

Batch Creation (Recommended for multi-collection setups)

批量创建(推荐用于多集合设置)

When creating 3+ collections (especially with relations), use import instead of individual create calls:
  1. Write a single JSON file with all collections
  2. Use collection names (not IDs) in
    collectionId
    for relation fields — PocketBase resolves them during import
  3. Import all at once
bash
python scripts/pb_collections.py import --file collections.json
Example
collections.json
:
json
{
  "collections": [
    {
      "name": "categories",
      "type": "base",
      "fields": [
        {"name": "name", "type": "text", "required": true}
      ]
    },
    {
      "name": "posts",
      "type": "base",
      "fields": [
        {"name": "title", "type": "text", "required": true},
        {"name": "category", "type": "relation", "collectionId": "categories", "maxSelect": 1}
      ],
      "listRule": "@request.auth.id != ''",
      "viewRule": "@request.auth.id != ''"
    }
  ],
  "deleteMissing": false
}
This replaces the Phase 1 (create without relations) → Phase 2 (get IDs) → Phase 3 (update with relations) workflow.
Import pitfalls:
  • Self-referencing relations (e.g.,
    parent
    field pointing to the same collection) fail on import because the collection doesn't exist yet when the relation is resolved. Use a 2-pass strategy: create the collection without the self-referencing field, then PATCH to add it:
    bash
    python scripts/pb_collections.py create '{"name":"categories","type":"base","fields":[{"name":"name","type":"text","required":true}]}'
    python scripts/pb_collections.py update categories '{"fields":[{"name":"name","type":"text","required":true},{"name":"parent","type":"relation","collectionId":"categories","maxSelect":1}]}'
  • Indexes must be SQL strings (e.g.,
    "CREATE INDEX idx_name ON posts (title)"
    ), not objects
  • Collection names are case-sensitive and must match exactly in
    collectionId
    references
当创建3个及以上集合(尤其是包含关联关系时),请使用导入而非单独创建:
  1. 编写包含所有集合的单个JSON文件
  2. 关联字段中使用集合名称(而非ID)作为
    collectionId
    — PocketBase会在导入时自动解析
  3. 一次性导入所有集合
bash
python scripts/pb_collections.py import --file collections.json
collections.json
示例:
json
{
  "collections": [
    {
      "name": "categories",
      "type": "base",
      "fields": [
        {"name": "name", "type": "text", "required": true}
      ]
    },
    {
      "name": "posts",
      "type": "base",
      "fields": [
        {"name": "title", "type": "text", "required": true},
        {"name": "category", "type": "relation", "collectionId": "categories", "maxSelect": 1}
      ],
      "listRule": "@request.auth.id != ''",
      "viewRule": "@request.auth.id != ''"
    }
  ],
  "deleteMissing": false
}
这替代了阶段1(无关联创建)→ 阶段2(获取ID)→ 阶段3(更新关联)的工作流。
导入注意事项:
  • 自引用关联(如指向同一集合的
    parent
    字段)在导入时会失败,因为解析关联时集合尚未存在。请使用两步策略:先创建无自引用字段的集合,再通过PATCH添加:
    bash
    python scripts/pb_collections.py create '{"name":"categories","type":"base","fields":[{"name":"name","type":"text","required":true}]}'
    python scripts/pb_collections.py update categories '{"fields":[{"name":"name","type":"text","required":true},{"name":"parent","type":"relation","collectionId":"categories","maxSelect":1}]}'
  • 索引必须为SQL字符串(如
    "CREATE INDEX idx_name ON posts (title)"
    ),而非对象
  • 集合名称区分大小写,
    collectionId
    引用必须完全匹配

Update

更新集合

bash
python scripts/pb_collections.py update posts '{"listRule":"@request.auth.id != '\'''\''","fields":[{"name":"title","type":"text","required":true},{"name":"content","type":"editor"},{"name":"status","type":"select","values":["draft","published"]}]}'
bash
python scripts/pb_collections.py update posts '{"listRule":"@request.auth.id != '\'''\''","fields":[{"name":"title","type":"text","required":true},{"name":"content","type":"editor"},{"name":"status","type":"select","values":["draft","published"]}]}'

Delete

删除集合

bash
python scripts/pb_collections.py delete posts
bash
python scripts/pb_collections.py delete posts

Import

导入集合

bash
python scripts/pb_collections.py import --file collections.json
collections.json
is a collections array, or
{"collections": [...], "deleteMissing": false}
format.
Details:
Read references/collections-api.md
— API rule syntax, all parameters.
bash
python scripts/pb_collections.py import --file collections.json
collections.json
可以是集合数组,或
{"collections": [...], "deleteMissing": false}
格式。
详细信息: 查看
references/collections-api.md
— API规则语法、所有参数。

4. Record Management

4. 记录管理

List

列出记录

bash
python scripts/pb_records.py list posts
python scripts/pb_records.py list posts --filter 'status="published"' --sort "-created" --expand "author" --page 1 --perPage 50
bash
python scripts/pb_records.py list posts
python scripts/pb_records.py list posts --filter 'status="published"' --sort "-created" --expand "author" --page 1 --perPage 50

Get

获取记录

bash
python scripts/pb_records.py get posts abc123def456789
python scripts/pb_records.py get posts abc123def456789 --expand "author,comments"
bash
python scripts/pb_records.py get posts abc123def456789
python scripts/pb_records.py get posts abc123def456789 --expand "author,comments"

Create

创建记录

bash
python scripts/pb_records.py create posts '{"title":"Hello World","content":"<p>My first post</p>","status":"draft"}'
python scripts/pb_records.py create posts --file record.json
bash
python scripts/pb_records.py create posts '{"title":"Hello World","content":"<p>My first post</p>","status":"draft"}'
python scripts/pb_records.py create posts --file record.json

Update

更新记录

bash
python scripts/pb_records.py update posts abc123def456789 '{"status":"published"}'
bash
python scripts/pb_records.py update posts abc123def456789 '{"status":"published"}'

Delete

删除记录

bash
python scripts/pb_records.py delete posts abc123def456789
bash
python scripts/pb_records.py delete posts abc123def456789

Filter Syntax Quick Reference

过滤语法快速参考

OperatorDescriptionExample
=
Equal
status = "published"
!=
Not equal
status != "draft"
>
,
>=
,
<
,
<=
Comparison
count > 10
~
Contains (LIKE)
title ~ "hello"
!~
Does not contain
title !~ "test"
?=
,
?~
etc.
Array/multi-value field
tags ?= "news"
Grouping:
(expr1 && expr2) || expr3
运算符描述示例
=
等于
status = "published"
!=
不等于
status != "draft"
>
,
>=
,
<
,
<=
比较
count > 10
~
包含(LIKE)
title ~ "hello"
!~
不包含
title !~ "test"
?=
,
?~
数组/多值字段
tags ?= "news"
分组:
(expr1 && expr2) || expr3

Sort

排序

-created
(DESC),
+title
(ASC),
@random
. Comma-separated for multiple fields.
-created
(降序)、
+title
(升序)、
@random
。多个字段用逗号分隔。

Expand (Relation Expansion)

展开(关联关系展开)

--expand "author"
— Direct relation.
--expand "author.profile"
— Nested relation (up to 6 levels).
--expand "author,category"
— Multiple relations.
Details:
Read references/records-api.md
— Batch operations, field selection, all operators.
--expand "author"
— 直接关联。
--expand "author.profile"
— 嵌套关联(最多6层)。
--expand "author,category"
— 多个关联。
详细信息: 查看
references/records-api.md
— 批量操作、字段选择、所有运算符。

5. Backup & Restore

5. 备份与恢复

bash
undefined
bash
undefined

List

列出备份

python scripts/pb_backups.py list
python scripts/pb_backups.py list

Create (omit name for auto-generated timestamp name)

创建备份(省略名称则使用自动生成的时间戳名称)

python scripts/pb_backups.py create python scripts/pb_backups.py create my_backup.zip
python scripts/pb_backups.py create python scripts/pb_backups.py create my_backup.zip

Restore (caution: replaces all data; server restart involved)

恢复备份(注意:会替换所有数据;涉及服务器重启)

python scripts/pb_backups.py restore pb_backup_20240101120000.zip
python scripts/pb_backups.py restore pb_backup_20240101120000.zip

Delete

删除备份

python scripts/pb_backups.py delete pb_backup_20240101120000.zip

**Notes:**
- Restore replaces all data (no merge)
- Server becomes temporarily unavailable during restore
- Always create a backup of current data before restoring

**Details:** `Read references/backups-api.md`
python scripts/pb_backups.py delete pb_backup_20240101120000.zip

**注意事项:**
- 恢复会替换所有数据(无合并)
- 恢复期间服务器会暂时不可用
- 恢复前请务必创建当前数据的备份

**详细信息:** 查看`references/backups-api.md`

6. Migrations

6. 迁移

Auto-Migration (Primary Workflow — Both Modes)

自动迁移(主要工作流 — 两种模式均适用)

PocketBase automatically generates migration files whenever you change a collection via the Admin UI or the API (e.g.,
pb_collections.py create/update
).
ModeAuto-generated file formatDirectoryRequirement
Standalone
.js
pb_migrations/
Enabled by default
Go package
.go
pb_migrations/
migratecmd.MustRegister()
with
Automigrate: true
Do NOT hand-write migration files for collection schema creation — use
pb_collections.py
and let PocketBase generate them.
Typical workflow (both modes):
  1. Start PocketBase (standalone:
    ./pocketbase serve
    , Go:
    go run . serve
    )
  2. Create/update collections via
    pb_collections.py create
    ,
    pb_collections.py import --file collections.json
    , or Admin UI
  3. PocketBase writes a timestamped migration file to
    pb_migrations/
  4. Commit the generated file to git
  5. On deploy, PocketBase runs pending migrations automatically at startup
Manual migration files are only for: seed data, data transforms, raw SQL, and superuser creation.
无论你通过Admin UI还是API(如
pb_collections.py create/update
)修改集合,PocketBase都会自动生成迁移文件
模式自动生成文件格式目录要求
独立模式
.js
pb_migrations/
默认启用
Go包模式
.go
pb_migrations/
migratecmd.MustRegister()
并设置
Automigrate: true
请勿手动编写集合架构创建的迁移文件 — 使用
pb_collections.py
并让PocketBase自动生成。
典型工作流(两种模式均适用):
  1. 启动PocketBase(独立模式:
    ./pocketbase serve
    ,Go模式:
    go run . serve
  2. 通过
    pb_collections.py create
    pb_collections.py import --file collections.json
    或Admin UI创建/更新集合
  3. PocketBase将时间戳命名的迁移文件写入
    pb_migrations/
  4. 将生成的文件提交至git
  5. 部署时,PocketBase会在启动时自动运行未执行的迁移
手动迁移文件仅适用于:种子数据、数据转换、原始SQL和超级用户创建

Manual Migration (for operations not auto-generated)

手动迁移(用于无法自动生成的操作)

Use
pb_create_migration.py
to generate an empty template when you need to write migration logic that the Admin UI cannot produce:
  • Data transformation (copy/reformat existing field values)
  • Raw SQL operations
  • Seed data insertion
  • Complex multi-step schema changes
bash
python scripts/pb_create_migration.py "backfill_user_slugs"
python scripts/pb_create_migration.py "seed_categories" --dir ./pb_migrations
Generates a file in
{timestamp}_{description}.js
format. Write migration logic in the
// === UP ===
and
// === DOWN ===
sections.
当你需要编写Admin UI无法完成的迁移逻辑时,使用
pb_create_migration.py
生成空模板:
  • 数据转换(复制/重新格式化现有字段值)
  • 原始SQL操作
  • 种子数据插入
  • 复杂的多步架构变更
bash
python scripts/pb_create_migration.py "backfill_user_slugs"
python scripts/pb_create_migration.py "seed_categories" --dir ./pb_migrations
生成
{timestamp}_{description}.js
格式的文件。在
// === UP ===
// === DOWN ===
部分编写迁移逻辑。

Common Patterns

常见模式

PatternUPDOWN
Create collection
new Collection({...})
+
app.save()
app.findCollectionByNameOrId()
+
app.delete()
Add field
collection.fields.add(new Field({...}))
collection.fields.removeByName()
Remove field
collection.fields.removeByName()
collection.fields.add(new Field({...}))
Change rules
collection.listRule = "..."
Revert to original rule
Execute SQL
app.db().newQuery("...").execute()
Reverse SQL
Seed data
new Record(collection)
+
app.save()
Delete records
Details:
Read references/migrations.md
— Code examples for all patterns. Field types:
Read references/field-types.md
— All field types and configuration options.
模式升级操作降级操作
创建集合
new Collection({...})
+
app.save()
app.findCollectionByNameOrId()
+
app.delete()
添加字段
collection.fields.add(new Field({...}))
collection.fields.removeByName()
删除字段
collection.fields.removeByName()
collection.fields.add(new Field({...}))
修改规则
collection.listRule = "..."
恢复为原始规则
执行SQL
app.db().newQuery("...").execute()
反向SQL操作
插入种子数据
new Record(collection)
+
app.save()
删除记录
详细信息: 查看
references/migrations.md
— 所有模式的代码示例。 字段类型: 查看
references/field-types.md
— 所有字段类型和配置选项。

7. Error Handling

7. 错误处理

All scripts output structured JSON:
json
{
  "success": true,
  "status": 200,
  "data": { ... }
}
所有脚本输出结构化JSON:
json
{
  "success": true,
  "status": 200,
  "data": { ... }
}

Common Error Codes

常见错误码

HTTP StatusMeaningResolution
400Bad RequestCheck request body. Validation error details in
data
field
401UnauthorizedToken expired. Scripts auto-retry
403ForbiddenOperation denied by API rules. Check rules
404Not FoundCollection or record does not exist
Validation error example:
json
{
  "success": false,
  "status": 400,
  "data": {
    "status": 400,
    "message": "Failed to create record.",
    "data": {
      "title": {
        "code": "validation_required",
        "message": "Missing required value."
      }
    }
  }
}
HTTP状态码含义解决方法
400错误请求检查请求体。
data
字段包含验证错误详情
401未授权令牌过期。脚本会自动重试
403禁止访问API规则拒绝操作。检查规则
404未找到集合或记录不存在
验证错误示例:
json
{
  "success": false,
  "status": 400,
  "data": {
    "status": 400,
    "message": "Failed to create record.",
    "data": {
      "title": {
        "code": "validation_required",
        "message": "Missing required value."
      }
    }
  }
}

8. Quick Reference

8. 快速参考

TaskScriptDetail Reference
Connection check
python scripts/pb_health.py
Superuser auth
python scripts/pb_auth.py
references/auth-api.md
User auth
python scripts/pb_auth.py --collection <name> --identity <email> --password <pw>
references/auth-api.md
List collections
python scripts/pb_collections.py list
references/collections-api.md
Get collection
python scripts/pb_collections.py get <name>
references/collections-api.md
Create collection
python scripts/pb_collections.py create '<json>'
references/collections-api.md
,
references/field-types.md
Update collection
python scripts/pb_collections.py update <name> '<json>'
references/collections-api.md
Delete collection
python scripts/pb_collections.py delete <name>
references/collections-api.md
Import collections
python scripts/pb_collections.py import --file <file>
references/collections-api.md
List records
python scripts/pb_records.py list <collection>
references/records-api.md
Get record
python scripts/pb_records.py get <collection> <id>
references/records-api.md
Create record
python scripts/pb_records.py create <collection> '<json>'
references/records-api.md
Update record
python scripts/pb_records.py update <collection> <id> '<json>'
references/records-api.md
Delete record
python scripts/pb_records.py delete <collection> <id>
references/records-api.md
List backups
python scripts/pb_backups.py list
references/backups-api.md
Create backup
python scripts/pb_backups.py create [name]
references/backups-api.md
Restore backup
python scripts/pb_backups.py restore <key>
references/backups-api.md
Delete backup
python scripts/pb_backups.py delete <key>
references/backups-api.md
Generate migration
python scripts/pb_create_migration.py "<description>"
references/migrations.md
API rules design
references/api-rules-guide.md
Common pitfalls
references/gotchas.md
Relation patterns
references/relation-patterns.md
JS SDK reference
references/js-sdk.md
JSVM hooks
references/jsvm-hooks.md
File handling
references/file-handling.md
Run E2E tests
python3 test_e2e.py
references/e2e-testing.md
E2E test helpersImport from
scripts/pb_e2e_helpers.py
references/e2e-testing.md
Go: build & run
go build -o myapp . && ./myapp serve
references/go-framework.md
Go: dev run
go run . serve
references/go-framework.md
Go: create superuser
go run . superuser create email pw
references/go-framework.md
Go: manual migration template (seed data / data transforms only)
assets/migration-template.go
references/go-migrations.md
任务脚本详细参考
连接检查
python scripts/pb_health.py
超级用户认证
python scripts/pb_auth.py
references/auth-api.md
用户认证
python scripts/pb_auth.py --collection <name> --identity <email> --password <pw>
references/auth-api.md
列出集合
python scripts/pb_collections.py list
references/collections-api.md
获取集合
python scripts/pb_collections.py get <name>
references/collections-api.md
创建集合
python scripts/pb_collections.py create '<json>'
references/collections-api.md
,
references/field-types.md
更新集合
python scripts/pb_collections.py update <name> '<json>'
references/collections-api.md
删除集合
python scripts/pb_collections.py delete <name>
references/collections-api.md
导入集合
python scripts/pb_collections.py import --file <file>
references/collections-api.md
列出记录
python scripts/pb_records.py list <collection>
references/records-api.md
获取记录
python scripts/pb_records.py get <collection> <id>
references/records-api.md
创建记录
python scripts/pb_records.py create <collection> '<json>'
references/records-api.md
更新记录
python scripts/pb_records.py update <collection> <id> '<json>'
references/records-api.md
删除记录
python scripts/pb_records.py delete <collection> <id>
references/records-api.md
列出备份
python scripts/pb_backups.py list
references/backups-api.md
创建备份
python scripts/pb_backups.py create [name]
references/backups-api.md
恢复备份
python scripts/pb_backups.py restore <key>
references/backups-api.md
删除备份
python scripts/pb_backups.py delete <key>
references/backups-api.md
生成迁移文件
python scripts/pb_create_migration.py "<description>"
references/migrations.md
API规则设计
references/api-rules-guide.md
常见陷阱
references/gotchas.md
关联关系模式
references/relation-patterns.md
JS SDK参考
references/js-sdk.md
JSVM钩子
references/jsvm-hooks.md
文件处理
references/file-handling.md
运行端到端测试
python3 test_e2e.py
references/e2e-testing.md
端到端测试辅助工具
scripts/pb_e2e_helpers.py
导入
references/e2e-testing.md
Go: 构建并运行
go build -o myapp . && ./myapp serve
references/go-framework.md
Go: 开发模式运行
go run . serve
references/go-framework.md
Go: 创建超级用户
go run . superuser create email pw
references/go-framework.md
Go: 手动迁移模板(仅适用于种子数据/数据转换)
assets/migration-template.go
references/go-migrations.md