Logo de Migration

Migration

Comunidade
ewtryocb
migration

Use when the user asks to create a database migration, change a SQLAlchemy model, add a column, add an index, or otherwise modify the schema. Enforces the rule that migrations are generated via `make generate NAME="..."` (the project's Makefile target that runs Alembic autogenerate) — never hand-written — and never edit existing migration files in migrations/versions/.

Visão geral

Publicado porewtryocb
Repositóriofastapi-claude-template
Nome da habilidademigration
Estrelas
33
Forks
5
Arquivos incluídos
Somente instruções
LicençaMIT
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    Habilidades de IA são Markdown simples, não código específico de um provedor, por isso funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Completa em si mesma

    Tudo de que o modelo precisa está nas instruções — sem arquivos extras para sincronizar.

  • Código aberto

    Publicada por ewtryocb no GitHub. Leia o conteúdo-fonte antes de instalar.

Instalação

Instale a habilidade de IA Migration no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL da pasta da habilidade exibida abaixo e confirme.
    https://github.com/ewtryocb/fastapi-claude-template/tree/master/.claude/skills/migration
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Nova habilidade → Via URL GitHub, depois cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/ewtryocb/fastapi-claude-template.git /tmp/fastapi-claude-template
mkdir -p .claude/skills
cp -r /tmp/fastapi-claude-template/.claude/skills/migration .claude/skills/migration
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Migration em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Migration automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Migration não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Creating database migrations

Migrations in this project are generated via the Makefile, which wraps Alembic's autogenerate. You never write migration files by hand, and you never edit an existing migration file.

The three Makefile targets

makefile
upgrade:    alembic upgrade head                # apply all pending migrations
downgrade:  alembic downgrade -1                # roll back the latest migration
generate:   alembic revision --autogenerate -m "$(NAME)"   # create a new migration

Run them from the repo root. The generate target requires a NAME variable — Alembic uses it as the migration message (and as part of the filename slug).

The standard workflow

When the user asks for a schema change, follow this exact order:

  1. Edit the SQLAlchemy model under src/database/psql/models/<entity>.py. Add/remove columns, indices, constraints, relationships — whatever the request needs.

  2. Update companion types under src/database/psql/types/<entity>.py:

    • If a new writable column: add it to Create<Entity>Type (required) and/or Update<Entity>Type (optional, total=False).
    • If a new relationship: add its name to <Entity>Loads = Literal[...].
  3. Generate the migration via the Makefile — do not call alembic directly:

    bash
    make generate NAME="add_is_verified_to_user"

    Alembic autogenerate will diff the model metadata against the current DB schema and write a new file to migrations/versions/NN_<hash>_add_is_verified_to_user.py. The NN_ numeric prefix is added by the project's naming convention — Alembic appends the hash + slug.

  4. Inspect the generated file. Autogenerate is imperfect — it often misses:

    • Column type changes (e.g. String(32) → String(64) may require manual alter_column with existing_type)
    • Index renames
    • Enum value additions (Postgres ALTER TYPE ... ADD VALUE)
    • server_default changes
    • Data migrations (filling a new NOT NULL column for existing rows)

    Open the generated file and verify the upgrade() and downgrade() functions match your intent. If anything is missing or wrong, edit the generated file now — it is fresh, uncommitted, not yet applied. Once a migration is applied to dev/staging/prod, it becomes immutable.

  5. Apply it locally:

    bash
    make upgrade
  6. Test it — run the relevant integration tests under tests/integration/ (they use testcontainers to spin up a real Postgres and apply migrations).

  7. Commit the model change, the types change, and the migration file in one commit. They must never be committed separately — a repo where models.py and migrations/versions/ disagree is broken.

Naming convention

Pass a snake_case, imperative-ish, description to NAME:

GoodBad
add_is_verified_to_user"added verified"
create_widget_table"widget"
rename_user_email_to_login"rename"
drop_legacy_permissions_column"cleanup"
add_gin_index_on_user_login"index"

Keep it under ~50 chars. The slug ends up in the filename and in git log, so it should stand alone.

What NOT to do

  • ❌ Do not write a new migration file by hand. Always use make generate NAME="...". Autogenerate is the starting point even if you'll have to edit it.
  • ❌ Do not call alembic revision --autogenerate directly. Use the Makefile target so the invocation is consistent across environments.
  • ❌ Do not edit an existing migration file in migrations/versions/ (01_...py, 02_...py, etc.). These are immutable history. A PreToolUse hook (.claude/hooks/guard_paths.py) blocks any edit to these files — if you see the block, you're doing something wrong. If you need to fix a bug in a migration that was already applied, write a new migration that corrects it; don't rewrite history.
  • ❌ Do not edit migrations/env.py casually — it's the Alembic bootstrap that the hook also protects. If you genuinely need to change it (e.g., to register a new metadata target), do it outside Claude's edit flow.
  • ❌ Do not apply a migration without generating + inspecting the file first. Autogenerate output is your audit trail — if you skip it, you lose traceability.
  • ❌ Do not autogenerate a migration against a schema that's out of sync with head. Run make upgrade first to bring the DB current, otherwise the diff will include changes from earlier, already-shipped migrations.

When autogenerate is not enough

Autogenerate is blind to:

  • Data migrations — if a new NOT NULL column needs a value for existing rows, you must write an op.execute("UPDATE ...") before the op.alter_column(..., nullable=False).
  • Enum mutations — Postgres enums need op.execute("ALTER TYPE <name> ADD VALUE '<val>'"); autogenerate doesn't emit this.
  • Complex index types — GIN, GiST, partial indexes, expression indexes may need hand-written op.create_index.
  • Check constraints with SQL expressions — autogenerate detects the constraint name but may miss the expression text.

For these cases: generate the migration normally, then edit the generated file (still allowed before commit) to add the missing op.execute(...) or op.create_index(...) calls, and update the downgrade() to reverse them.

Rollback discipline

Every upgrade() must have a real downgrade(). Never leave pass in downgrade() unless the operation is genuinely irreversible (and even then, prefer raising NotImplementedError to make the intent explicit).

Checklist (run this before handing back to the user)

  • Edited the model in src/database/psql/models/<entity>.py
  • Updated Create<Entity>Type / Update<Entity>Type / <Entity>Loads in src/database/psql/types/<entity>.py if applicable
  • Ran make generate NAME="<snake_case_desc>"
  • Opened the generated file and verified upgrade() / downgrade() match intent
  • Added any missing data migrations, enum ops, or custom index calls
  • Ran make upgrade locally
  • Ran the relevant integration tests
  • Staged model + types + migration together for one commit

Perguntas frequentes

O que a habilidade de IA Migration faz?

Use when the user asks to create a database migration, change a SQLAlchemy model, add a column, add an index, or otherwise modify the schema. Enforces the rule that migrations are generated via `make generate NAME="..."` (the project's Makefile target that runs Alembic autogenerate) — never hand-written — and never edit existing migration files in migrations/versions/.

Por que usar Migration no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. Migration é escrito em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. O TypingMind usa suas próprias chaves de API, então o pagamento é feito diretamente aos provedores, em vez de uma assinatura por licença de usuário, e suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Migration no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/ewtryocb/fastapi-claude-template/tree/master/.claude/skills/migration. O TypingMind lê o arquivo SKILL.md e instala a habilidade para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Migration?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Migration?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Migration com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Migration é gratuita?

Sim. A habilidade é publicada no GitHub por ewtryocb sob a licença MIT. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, modelos de documento ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas para chamar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA fornece conhecimento e um processo ao modelo: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver todos

Crie seu próprio espaço de IA agora

Inscreva-se na nossa newsletter para receber novidades sobre recursos e futuros sorteios 👇