pocketbase
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePocketBase 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: — Python scripts for API operations
scripts/ - References: — Detailed docs loaded on demand
references/ - Assets: — Templates and static files
assets/
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.
本技能的所有资源都打包在技能目录中:
- 脚本:— 用于API操作的Python脚本
scripts/ - 参考文档:— 按需加载的详细文档
references/ - 资源文件:— 模板和静态文件
assets/
当你需要查询PocketBase细节或查找技能相关文件时,请先查看此目录——所需内容均已包含在内,无需搜索用户主目录或其他项目。
Mode Detection
模式检测
Determine the project mode:
- exists and contains
go.mod→ Go package modegithub.com/pocketbase/pocketbase - 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 (, etc.) and E2E tests work as-is.
pb_collections.py判断项目模式:
- 存在且包含
go.mod→ Go包模式github.com/pocketbase/pocketbase - 否则 → 独立模式(现有工作流)
Go包模式额外参考文档:
- 配置与结构 → 查看
references/go-framework.md - 迁移 → 查看
references/go-migrations.md - 钩子与自定义路由 → 查看
references/go-hooks-routes.md
Go包模式仍可使用相同的REST API。Python脚本(如等)和端到端测试可直接使用。
pb_collections.py0. Design Workflow & Decision Making
0. 设计工作流与决策制定
Read 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 wrapper) and collection key is (not ).
references/gotchas.mdoptionsfieldsschema在编写任何PocketBase代码前,请先阅读
你的训练数据包含已过时的v0.22模式,这些模式在v0.23+版本中会失效。
检查字段JSON:确保属性为扁平结构(无包装器),且集合使用键(而非)。
references/gotchas.mdoptionsfieldsschema⚠️ v0.22 Anti-Patterns — DO NOT USE
⚠️ v0.22 反模式 — 请勿使用
Field properties must be FLAT — wrapper was removed in v0.23+:
optionsjson
// 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: (values, maxSelect), (maxSelect, maxSize, mimeTypes, thumbs), (collectionId, maxSelect), (min, max, pattern).
selectfilerelationtextThis flat-property rule applies everywhere — inline JSON in , files used with , and Go migration code. If you see in any PocketBase field definition, it is WRONG.
pb_collections.py createcollections.jsonpb_collections.py import"options": {Collection JSON: use key, not :
fieldsschemajson
// WRONG: {"name": "posts", "type": "base", "schema": [...]}
// CORRECT: {"name": "posts", "type": "base", "fields": [...]}Migration JS: use typed constructors, not :
SchemaFieldjs
// 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 wrapper)
options - Collection JSON uses key (not
fields)schema - Migrations use typed constructors (,
SelectField,TextField, etc.)RelationField - Hooks use and
e.next()(not$app.findRecordById())$app.dao() - Routes use syntax (not
{paramName}):paramName - references in API rules use
@collection(not?=) —=breaks with 2+ rows=
Go package mode additional checks:
- Collections created via (not hand-written migration files)
pb_collections.py - Auto-generated migration files in are committed to git
pb_migrations/ - with
migratecmd.MustRegister()(dev) is configured inAutomigrate: truemain.go - blank import exists in
_ "yourmodule/migrations"(if manual migrations are used)main.go - Manual migration files (seed data, data transforms) use +
package migrations+func init()m.Register() - Rules set with (not direct string assignment —
types.Pointer("rule")type)*string - Hooks call (omitting causes request hang)
return e.Next()
字段属性必须为扁平结构 — v0.23+已移除包装器:
optionsjson
// 错误写法(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}此规则适用于所有字段类型:(values、maxSelect)、(maxSelect、maxSize、mimeTypes、thumbs)、(collectionId、maxSelect)、(min、max、pattern)。
selectfilerelationtext此扁平属性规则适用于所有场景 —— 中的内联JSON、使用的文件,以及Go迁移代码。如果在任何PocketBase字段定义中看到,均为错误写法。
pb_collections.py createpb_collections.py importcollections.json"options": {集合JSON:使用键,而非:
fieldsschemajson
// 错误写法:{"name": "posts", "type": "base", "schema": [...]}
// 正确写法:{"name": "posts", "type": "base", "fields": [...]}JS迁移:使用类型化构造函数,而非:
SchemaFieldjs
// 错误写法: 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 - 中自动生成的迁移文件已提交至git
pb_migrations/ - 中配置了
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:
- 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 - Create superuser —
./pocketbase superuser create admin@example.com <password> - Write — Confirm credentials with user, write
.env, add to.env.gitignore - Start —
nohup ./pocketbase serve --http=127.0.0.1:8090 > pb.log 2>&1 & - Verify —
python scripts/pb_health.py
当PocketBase尚未运行时:
- 下载 — 获取最新版本:
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 - 创建超级用户 —
./pocketbase superuser create admin@example.com <password> - 编写文件 — 与用户确认凭据,编写
.env并添加至.env.gitignore - 启动 —
nohup ./pocketbase serve --http=127.0.0.1:8090 > pb.log 2>&1 & - 验证 —
python scripts/pb_health.py
Design Decision Tree
设计决策流程
When building a PocketBase application, follow this sequence:
- Requirements — Identify entities, relationships, and access patterns
- Collection types — Choose ,
base, orauthfor each entityview - Fields — Design fields per collection ()
Read references/field-types.md - Relations — Design relations ()
Read references/relation-patterns.md - API rules — Set security rules ()
Read references/api-rules-guide.md- Default to (deny all). Open only what is needed.
null - = superuser only,
null= anyone including guests""
- Default to
- Create — Create collections via Python scripts (both modes)
- Use or
pb_collections.py createpb_collections.py import --file collections.json - PocketBase auto-generates migration files (in standalone,
.jsin Go package mode with.go)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 (), Go uses Go code —
pb_hooks/*.pb.jsRead references/go-hooks-routes.md
- Use
- Seed data — Insert sample records for verification
- Test — Use Python E2E tests for all integration testing:
- Read
references/e2e-testing.md - Use module
pb_e2e_helpers - 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
- Read
- Verify — Run self-tests (see below)
构建PocketBase应用时,请遵循以下步骤:
- 需求分析 — 确定实体、关联关系和访问模式
- 集合类型选择 — 为每个实体选择、
base或auth类型view - 字段设计 — 为每个集合设计字段(查看)
references/field-types.md - 关联关系设计 — 设计关联关系(查看)
references/relation-patterns.md - API规则设置 — 配置安全规则(查看)
references/api-rules-guide.md- 默认设置为(拒绝所有访问)。仅开放必要权限。
null - = 仅超级用户可访问,
null= 任何人(包括访客)均可访问""
- 默认设置为
- 创建集合 — 通过Python脚本创建集合(两种模式均适用)
- 使用或
pb_collections.py createpb_collections.py import --file collections.json - PocketBase会自动生成迁移文件(独立模式下为,Go包模式且
.js时为Automigrate: true).go - 将自动生成的迁移文件提交至git
- 请勿手动编写集合架构创建的迁移文件 — 让PocketBase自动生成
- 数据转换、种子数据或原始SQL操作,请查看第6节(迁移)
- 钩子/路由:独立模式使用JSVM(),Go模式使用Go代码 — 查看
pb_hooks/*.pb.jsreferences/go-hooks-routes.md
- 使用
- 种子数据插入 — 插入示例记录用于验证
- 测试 — 使用Python端到端测试进行所有集成测试:
- 查看
references/e2e-testing.md - 使用模块
pb_e2e_helpers - 测试每个集合API规则的正向和负向访问
- 自定义路由和钩子(Go或JSVM)也需进行端到端测试 — 调用HTTP端点并验证响应
- 不依赖PocketBase的纯函数(工具、验证、转换逻辑)可使用标准
go test
- 查看
- 验证 — 运行自测试(见下文)
Self-Test Verification
自测试验证
After creating or modifying collections:
- Confirm schema:
pb_collections.py get <name> - CRUD smoke test: create → list → get → update → delete
- Rule verification: test as non-superuser
- Use
pb_auth.py --collection users --identity ... --password ... - Verify denied access returns expected behavior
- Use
- E2E test — Required when any collection has a non-API rule, or when custom routes/hooks exist:
nullRead references/e2e-testing.md- Generate a test script () in the project root using
test_e2e.pymodulepb_e2e_helpers - 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 contains
createRule, verify that setting X to a different user's ID is rejected@request.body.X = @request.auth.id - behavior — deleting a parent removes related child records
cascadeDelete - rule (superuser-only) endpoints return 403 for regular users
null - 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
创建或修改集合后:
- 确认架构:
pb_collections.py get <name> - CRUD冒烟测试:创建 → 列表 → 获取 → 更新 → 删除
- 规则验证:以非超级用户身份测试
- 使用
pb_auth.py --collection users --identity ... --password ... - 验证被拒绝的访问是否返回预期行为
- 使用
- 端到端测试 — 当任何集合的API规则非,或存在自定义路由/钩子时必须执行:
null- 查看
references/e2e-testing.md - 使用模块在项目根目录生成测试脚本(
pb_e2e_helpers)test_e2e.py - 测试必须覆盖:
- 未认证访问被拒绝(预期返回401/403)
- 已认证用户可执行允许的操作
- 用户无法访问其他用户的资源(跨用户隔离)
- 防伪造 — 如果包含
createRule,验证将X设置为其他用户ID会被拒绝@request.body.X = @request.auth.id - 行为 — 删除父记录会移除相关子记录
cascadeDelete - 规则(仅超级用户可访问)的端点对普通用户返回403
null - 自定义路由:有效请求返回正确响应,认证中间件拒绝未认证/未授权请求
- 钩子副作用:验证钩子触发后的预期数据库状态或响应
- 运行测试并修复所有失败项后,方可标记任务完成
- 查看
Reference Index
参考文档索引
| Topic | Reference |
|---|---|
| Gotchas & pitfalls | |
| API rules design | |
| Relation patterns | |
| JS SDK (frontend) | |
| JSVM hooks (server) | |
| File handling | |
| E2E testing patterns | |
| Go framework setup | |
| Go migrations | |
| Go hooks & routes | |
| Production deployment (Docker, binary, proxy) | |
| React SPA frontend | |
| 主题 | 参考文档 |
|---|---|
| 常见陷阱 | |
| API规则设计 | |
| 关联关系模式 | |
| JS SDK(前端) | |
| JSVM钩子(服务端) | |
| 文件处理 | |
| 端到端测试模式 | |
| Go框架配置 | |
| Go迁移 | |
| Go钩子与路由 | |
| 生产部署(Docker、二进制、代理) | |
| 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}.zipPlatform asset names:
| Platform | Asset name |
|---|---|
| Linux amd64 | |
| Linux arm64 | |
| macOS amd64 | |
| macOS arm64 (Apple Silicon) | |
| Windows amd64 | |
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 | |
| Linux arm64 | |
| macOS amd64 | |
| macOS arm64(Apple Silicon) | |
| Windows amd64 | |
下载、解压并启动:
bash
undefinedExample 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 yourpasswordStarting PocketBase in background (for Claude Code sessions):
bash
undefinedVERSION=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
undefinedStart 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
环境变量
| Variable | Required | Default | Description |
|---|---|---|---|
| No | | PocketBase base URL |
| Yes* | — | Superuser email address |
| Yes* | — | Superuser password |
*Required when performing superuser operations.
If environment variables are not set, the 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).
.envenv
PB_URL=http://127.0.0.1:8090
PB_SUPERUSER_EMAIL=admin@example.com
PB_SUPERUSER_PASSWORD=your-passwordImportant: If environment variables are not set, confirm the values with the user before executing operations. When writing credentials to a file, ensure that is included in .
.env.env.gitignore| 变量 | 是否必填 | 默认值 | 描述 |
|---|---|---|---|
| 否 | | PocketBase基础URL |
| 是* | — | 超级用户邮箱地址 |
| 是* | — | 超级用户密码 |
*执行超级用户操作时必填。
如果未设置环境变量,将从当前工作目录加载文件。如果未找到,将向上搜索父目录直至文件系统根目录(适用于单体仓库设置,脚本可能从子目录运行)。
.envenv
PB_URL=http://127.0.0.1:8090
PB_SUPERUSER_EMAIL=admin@example.com
PB_SUPERUSER_PASSWORD=your-password重要提示: 如果未设置环境变量,执行操作前请与用户确认值。将凭据写入文件时,确保已添加至。
.env.env.gitignorepb_config.py
Exports
pb_config.pypb_config.py
导出项
pb_config.pyAll PB scripts share this module. Available exports:
| Export | Type | Description |
|---|---|---|
| | PocketBase base URL (from env or default |
| | Superuser email (from env) |
| | Superuser password (from env) |
| function | Low-level HTTP request to PB API |
| function | Auto-authenticated superuser request (retries on 401) |
| function | Get cached superuser bearer token |
| function | Print structured JSON output |
| exception | Raised on HTTP errors (has |
Do not invent exports that don't exist (e.g.,). Check this table or readget_configdirectly.pb_config.py
所有PB脚本共享此模块。可用导出项:
| 导出项 | 类型 | 描述 |
|---|---|---|
| | PocketBase基础URL(来自环境变量或默认值 |
| | 超级用户邮箱(来自环境变量) |
| | 超级用户密码(来自环境变量) |
| 函数 | 向PB API发送底层HTTP请求 |
| 函数 | 自动认证的超级用户请求(401时重试) |
| 函数 | 获取缓存的超级用户Bearer令牌 |
| 函数 | 打印结构化JSON输出 |
| 异常 | HTTP错误时抛出(包含 |
请勿虚构不存在的导出项(如)。请查看此表格或直接阅读get_config。pb_config.py
Connection Check
连接检查
bash
python scripts/pb_health.pyRuns 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.pyAuthenticates using and via . Returns a token.
PB_SUPERUSER_EMAILPB_SUPERUSER_PASSWORDPOST /api/collections/_superusers/auth-with-passwordbash
python scripts/pb_auth.py通过使用和进行认证,返回令牌。
POST /api/collections/_superusers/auth-with-passwordPB_SUPERUSER_EMAILPB_SUPERUSER_PASSWORDUser Authentication
用户认证
bash
python scripts/pb_auth.py --collection users --identity user@example.com --password secretAuthenticates 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: — OAuth2, impersonate, password reset, etc.
Read references/auth-api.md每个脚本内部会自动获取并缓存超级用户令牌。遇到401错误时,会重新认证一次。
详细信息: 查看 — OAuth2、模拟、密码重置等。
references/auth-api.md3. 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_1234567890bash
python scripts/pb_collections.py get posts
python scripts/pb_collections.py get pbc_1234567890Create
创建集合
bash
undefinedbash
undefinedInline 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:
- Write a single JSON file with all collections
- Use collection names (not IDs) in for relation fields — PocketBase resolves them during import
collectionId - Import all at once
bash
python scripts/pb_collections.py import --file collections.jsonExample :
collections.jsonjson
{
"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., 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:
parentbashpython 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., ), not objects
"CREATE INDEX idx_name ON posts (title)" - Collection names are case-sensitive and must match exactly in references
collectionId
当创建3个及以上集合(尤其是包含关联关系时),请使用导入而非单独创建:
- 编写包含所有集合的单个JSON文件
- 关联字段中使用集合名称(而非ID)作为— PocketBase会在导入时自动解析
collectionId - 一次性导入所有集合
bash
python scripts/pb_collections.py import --file collections.jsoncollections.jsonjson
{
"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(更新关联)的工作流。
导入注意事项:
- 自引用关联(如指向同一集合的字段)在导入时会失败,因为解析关联时集合尚未存在。请使用两步策略:先创建无自引用字段的集合,再通过PATCH添加:
parentbashpython 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 postsbash
python scripts/pb_collections.py delete postsImport
导入集合
bash
python scripts/pb_collections.py import --file collections.jsoncollections.json{"collections": [...], "deleteMissing": false}Details: — API rule syntax, all parameters.
Read references/collections-api.mdbash
python scripts/pb_collections.py import --file collections.jsoncollections.json{"collections": [...], "deleteMissing": false}详细信息: 查看 — API规则语法、所有参数。
references/collections-api.md4. 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 50bash
python scripts/pb_records.py list posts
python scripts/pb_records.py list posts --filter 'status="published"' --sort "-created" --expand "author" --page 1 --perPage 50Get
获取记录
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.jsonbash
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.jsonUpdate
更新记录
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 abc123def456789bash
python scripts/pb_records.py delete posts abc123def456789Filter Syntax Quick Reference
过滤语法快速参考
| Operator | Description | Example |
|---|---|---|
| Equal | |
| Not equal | |
| Comparison | |
| Contains (LIKE) | |
| Does not contain | |
| Array/multi-value field | |
Grouping:
(expr1 && expr2) || expr3| 运算符 | 描述 | 示例 |
|---|---|---|
| 等于 | |
| 不等于 | |
| 比较 | |
| 包含(LIKE) | |
| 不包含 | |
| 数组/多值字段 | |
分组:
(expr1 && expr2) || expr3Sort
排序
-created+title@random-created+title@randomExpand (Relation Expansion)
展开(关联关系展开)
--expand "author"--expand "author.profile"--expand "author,category"Details: — Batch operations, field selection, all operators.
Read references/records-api.md--expand "author"--expand "author.profile"--expand "author,category"详细信息: 查看 — 批量操作、字段选择、所有运算符。
references/records-api.md5. Backup & Restore
5. 备份与恢复
bash
undefinedbash
undefinedList
列出备份
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| Mode | Auto-generated file format | Directory | Requirement |
|---|---|---|---|
| Standalone | | | Enabled by default |
| Go package | | | |
Do NOT hand-write migration files for collection schema creation — use and let PocketBase generate them.
pb_collections.pyTypical workflow (both modes):
- Start PocketBase (standalone: , Go:
./pocketbase serve)go run . serve - Create/update collections via ,
pb_collections.py create, or Admin UIpb_collections.py import --file collections.json - PocketBase writes a timestamped migration file to
pb_migrations/ - Commit the generated file to git
- 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(如)修改集合,PocketBase都会自动生成迁移文件。
pb_collections.py create/update| 模式 | 自动生成文件格式 | 目录 | 要求 |
|---|---|---|---|
| 独立模式 | | | 默认启用 |
| Go包模式 | | | |
请勿手动编写集合架构创建的迁移文件 — 使用并让PocketBase自动生成。
pb_collections.py典型工作流(两种模式均适用):
- 启动PocketBase(独立模式:,Go模式:
./pocketbase serve)go run . serve - 通过、
pb_collections.py create或Admin UI创建/更新集合pb_collections.py import --file collections.json - PocketBase将时间戳命名的迁移文件写入
pb_migrations/ - 将生成的文件提交至git
- 部署时,PocketBase会在启动时自动运行未执行的迁移
手动迁移文件仅适用于:种子数据、数据转换、原始SQL和超级用户创建。
Manual Migration (for operations not auto-generated)
手动迁移(用于无法自动生成的操作)
Use to generate an empty template when you need to write migration logic that the Admin UI cannot produce:
pb_create_migration.py- 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_migrationsGenerates a file in format. Write migration logic in the and sections.
{timestamp}_{description}.js// === UP ===// === DOWN ===当你需要编写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
常见模式
| Pattern | UP | DOWN |
|---|---|---|
| Create collection | | |
| Add field | | |
| Remove field | | |
| Change rules | | Revert to original rule |
| Execute SQL | | Reverse SQL |
| Seed data | | Delete records |
Details: — Code examples for all patterns.
Field types: — All field types and configuration options.
Read references/migrations.mdRead references/field-types.md| 模式 | 升级操作 | 降级操作 |
|---|---|---|
| 创建集合 | | |
| 添加字段 | | |
| 删除字段 | | |
| 修改规则 | | 恢复为原始规则 |
| 执行SQL | | 反向SQL操作 |
| 插入种子数据 | | 删除记录 |
详细信息: 查看 — 所有模式的代码示例。
字段类型: 查看 — 所有字段类型和配置选项。
references/migrations.mdreferences/field-types.md7. 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 Status | Meaning | Resolution |
|---|---|---|
| 400 | Bad Request | Check request body. Validation error details in |
| 401 | Unauthorized | Token expired. Scripts auto-retry |
| 403 | Forbidden | Operation denied by API rules. Check rules |
| 404 | Not Found | Collection 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 | 错误请求 | 检查请求体。 |
| 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. 快速参考
| Task | Script | Detail Reference |
|---|---|---|
| Connection check | | — |
| Superuser auth | | |
| User auth | | |
| List collections | | |
| Get collection | | |
| Create collection | | |
| Update collection | | |
| Delete collection | | |
| Import collections | | |
| List records | | |
| Get record | | |
| Create record | | |
| Update record | | |
| Delete record | | |
| List backups | | |
| Create backup | | |
| Restore backup | | |
| Delete backup | | |
| Generate migration | | |
| API rules design | — | |
| Common pitfalls | — | |
| Relation patterns | — | |
| JS SDK reference | — | |
| JSVM hooks | — | |
| File handling | — | |
| Run E2E tests | | |
| E2E test helpers | Import from | |
| Go: build & run | | |
| Go: dev run | | |
| Go: create superuser | | |
| Go: manual migration template (seed data / data transforms only) | | |
| 任务 | 脚本 | 详细参考 |
|---|---|---|
| 连接检查 | | — |
| 超级用户认证 | | |
| 用户认证 | | |
| 列出集合 | | |
| 获取集合 | | |
| 创建集合 | | |
| 更新集合 | | |
| 删除集合 | | |
| 导入集合 | | |
| 列出记录 | | |
| 获取记录 | | |
| 创建记录 | | |
| 更新记录 | | |
| 删除记录 | | |
| 列出备份 | | |
| 创建备份 | | |
| 恢复备份 | | |
| 删除备份 | | |
| 生成迁移文件 | | |
| API规则设计 | — | |
| 常见陷阱 | — | |
| 关联关系模式 | — | |
| JS SDK参考 | — | |
| JSVM钩子 | — | |
| 文件处理 | — | |
| 运行端到端测试 | | |
| 端到端测试辅助工具 | 从 | |
| Go: 构建并运行 | | |
| Go: 开发模式运行 | | |
| Go: 创建超级用户 | | |
| Go: 手动迁移模板(仅适用于种子数据/数据转换) | | |