Pular para o conteúdo
Skillpedia
APIs e servidores (backend)33 mil · #8874

pb-migrations

O que ela faz

Esta skill ajuda você a registrar e aplicar mudanças na estrutura de um banco PocketBase ao longo do tempo. Ela é voltada para desenvolvedores que trabalham entre desenvolvimento e produção e querem as mudanças de esquema registradas.

Quando usar

  • ✓Quando você altera coleções e quer que a mudança fique registrada em um arquivo de migração.
  • ✓Quando você precisa aplicar o mesmo esquema em um segundo ambiente.
  • ✓Quando você quer desativar a migração automática para a produção.

Link da skill

https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/pocketbase/pb-migrations/SKILL.md

Copie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.

Como usar

O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.

Mensagem pronta para colar

Use esta skill para me ajudar: https://github.com/davila7/claude-code-templates/blob/main/cli-tool/components/skills/pocketbase/pb-migrations/SKILL.md Leia o arquivo SKILL.md desse link e siga as instruções dele na minha tarefa.
Quer que a sua IA encontre skills como esta sozinha?Instale o MCP grátis do Skillpedia: uma linha, e ela pesquisa entre 15.000+ skills antes de cada tarefa.Instalar em 1 minuto →

Exemplo do que pedir para a IA

“Alterei as coleções do meu PocketBase em desenvolvimento. Crie os arquivos de migração para que a produção receba o mesmo esquema.”

5 skills novas por semana. 1 minuto de leitura.

Como funciona

O agente usa os comandos de migração para criar, aplicar, reverter ou gerar snapshots de migrações, e mantém os arquivos de migração sob controle de versão para que cada ambiente execute as mesmas mudanças.

Conteúdo técnico (SKILL.md original)

Texto original do autor, em inglês, direto do GitHub.

PocketBase Migrations & Schema Versioning

Overview

PocketBase supports two approaches to schema management:

  1. Auto-migrate (default in dev) — Dashboard changes auto-generate migration files in pb_migrations/
  2. Manual migrations — write migration files by hand for full control

CLI Commands

# Create a new empty migration file
./pocketbase migrate create "add_posts_collection"
# Creates: pb_migrations/1234567890_add_posts_collection.js

# Apply all pending migrations
./pocketbase migrate up

# Revert the last applied migration
./pocketbase migrate down

# Generate a full snapshot of all current collections
./pocketbase migrate collections
# Creates a migration file that recreates all collections from scratch

# Sync migration history with actual DB state (mark all as applied)
./pocketbase migrate history-sync

Auto-migrate Mode

Enabled by default. When you change collections in the Dashboard, PocketBase auto-generates migration files in pb_migrations/.

# Start with auto-migrate (default)
./pocketbase serve

# Disable auto-migrate (production)
./pocketbase serve --automigrate=0

Workflow:

  1. Develop with auto-migrate ON — use Dashboard to design schema
  2. Migration files are auto-generated in pb_migrations/
  3. Commit these files to git
  4. Deploy: migrations run automatically on serve start
  5. In production: use --automigrate=0 to prevent Dashboard changes from generating new migrations

Migration File Format

// pb_migrations/1234567890_add_posts_collection.js

migrate(
    // UP — apply migration
    function(app) {
        var collection = new Collection({
            name: "posts",
            type: "base",
            fields: [
                { name: "title", type: "text", required: true },
                { name: "body", type: "editor" },
                { name: "author", type: "relation", collectionId: "USERS_COLLECTION_ID", cascadeDelete: false, maxSelect: 1, required: true },
                { name: "status", type: "select", values: ["draft", "published", "archived"] },
                { name: "published_at", type: "date" },
                { name: "tags", type: "relation", collectionId: "TAGS_COLLECTION_ID", maxSelect: 0 }
            ],
            indexes: [
                "CREATE INDEX idx_posts_author ON posts (author)",
                "CREATE INDEX idx_posts_status ON posts (status)",
                "CREATE UNIQUE INDEX idx_posts_title ON posts (title)"
            ],
            listRule: "",   // WARNING: "" means public access — use a filter or null to restrict
            viewRule: "",   // WARNING: "" means public access — use a filter or null to restrict
            createRule: "@request.auth.id != ''",
            updateRule: "author = @request.auth.id",
            deleteRule: "author = @request.auth.id"
        })
        app.save(collection)
    },
    // DOWN — revert migration
    function(app) {
        var collection = app.findCollectionByNameOrId("posts")
        app.delete(collection)
    }
)

Important: the app inside migrations is a transactional instance. If any error occurs, the entire migration is rolled back.

Creating Collections Programmatically

Base collection

var collection = new Collection({
    name: "posts",
    type: "base",
    fields: [
        { name: "title", type: "text", required: true, min: 3, max: 200 },
        { name: "slug", type: "text", required: true, autogenerate: { pattern: "slugify(title)" } },
        { name: "body", type: "editor" },
        { name: "cover", type: "file", maxSelect: 1, maxSize: 5242880, mimeTypes: ["image/jpeg", "image/png", "image/webp"] },
        { name: "views", type: "number", min: 0 },
        { name: "metadata", type: "json", maxSize: 2000000 },
        { name: "featured", type: "bool" },
        { name: "published_at", type: "date" }
    ]
})
app.save(collection)

Auth collection

var collection = new Collection({
    name: "users",
    type: "auth",
    fields: [
        { name: "name", type: "text", required: true },
        { name: "avatar", type: "file", maxSelect: 1, maxSize: 5242880 },
        { name: "role", type: "select", values: ["user", "editor", "admin"], required: true }
    ],
    passwordAuth: { enabled: true, identityFields: ["email", "username"] },
    oauth2: { enabled: true },
    otp: { enabled: false },
    mfa: { enabled: false },
    authToken: { duration: 604800 }  // 7 days
})
app.save(collecti
Perguntas frequentes

O PocketBase cria migrações automaticamente?

Por padrão, sim, em desenvolvimento. As mudanças feitas no painel geram arquivos de migração, que você pode então fazer commit.

Como desativo a migração automática em produção?

A skill mostra que você pode iniciar o servidor com a migração automática desligada.

Posso desfazer uma migração?

Sim. O comando migrate down reverte a migração aplicada mais recentemente.

Detalhes

Descrição original do autor

Schema migrations and versioning for PocketBase. Use when creating migrations, managing schema versions, syncing collections between environments, using automigrate, or creating collections programmatically. Covers migrate commands, migration file format, snapshot imports, and the _migrations tracking table.

repo: davila7/claude-code-templates

Popularidade

Estrelas no GitHub
33 mil
Posição no ranking
#8874
Licença
MIT
Atualizada em
02/11/2026

Essa skill é útil?

0

Entre para votar.

Comentários

  • …

Mais skills deste repositório

Skills parecidas