{
  "id": "claude-code-rules-for-prisma-projects",
  "type": "rules",
  "category": "rules",
  "locale": "pt",
  "url": "/pt/rules/claude-code-rules-for-prisma-projects",
  "title": "Regras do Claude Code para Projetos Prisma",
  "description": "Regras do Claude Code para projetos com Prisma ORM, abordando segurança de migrações, padrões de consulta, carregamento de relações e prevenção de corrupção do schema por agentes.",
  "tools": [
    "Claude Code",
    "Cursor",
    "Codex"
  ],
  "stack": [
    "Next.js",
    "PostgreSQL",
    "TypeScript"
  ],
  "tags": [
    "agents-md",
    "postgres",
    "typescript",
    "conventions",
    "security"
  ],
  "difficulty": null,
  "updated": "2026-06-08",
  "markdown": "Adicione isso como um arquivo `CLAUDE.md` na raiz do seu repositório. O Claude Code lê `CLAUDE.md` automaticamente (além de `AGENTS.md`) e o aplica como instruções de nível de projeto para cada sessão.\n\n## Arquivo de Regras do Claude Code\n\n```txt title=\"Claude Code Rules\"\n# Prisma Project Rules\n\n## Schema rules — highest risk area\n- NEVER edit `prisma/schema.prisma` without explicitly confirming the change with the\n  developer first. Schema changes generate migrations that alter production data.\n- When asked to add a field, propose the schema diff and the migration name, then\n  STOP and wait for approval before running `prisma migrate dev`.\n- New required fields MUST have a `@default(...)` value or be added as optional\n  (`String?`). Adding a required field without a default breaks `migrate deploy` on\n  a non-empty database.\n- Do NOT add `@@map` or `@map` attributes to rename existing tables or columns without\n  explicitly discussing the migration strategy — renames require data migration steps.\n- Use `@db.Text` for long strings, `@db.VarChar(n)` for bounded strings. Never use\n  bare `String` for fields that will store user-generated content longer than 255 chars.\n\n## Migration rules\n- Run `prisma migrate dev --name <descriptive-name>` to generate migrations locally.\n  Never hand-edit files in `prisma/migrations/` — they are append-only.\n- In CI/CD, run `prisma migrate deploy` (not `migrate dev`). Never run `migrate dev`\n  against a production database.\n- After adding or changing models, always regenerate the client: `prisma generate`.\n  Never commit code that imports from `@prisma/client` without a matching `generate` run.\n\n## Query patterns\n- Import the Prisma client from `src/lib/prisma.ts` (the singleton). Never instantiate\n  `new PrismaClient()` in application code — this leaks connections in serverless.\n- Use `select` or `include` explicitly on every query. Never rely on Prisma's default\n  select-all behaviour — it causes over-fetching and leaks sensitive fields.\n- Paginate all list queries with `take` and `skip` (or cursor-based pagination with\n  `cursor` + `take`). Never run a `findMany` without a limit on a user-facing endpoint.\n- Wrap multi-step mutations in `prisma.$transaction([...])` or the interactive\n  transaction callback. Never perform two sequential writes that must be atomic outside\n  a transaction.\n- Use `prisma.$queryRaw` and `Prisma.sql` template tag for raw SQL only. Never\n  concatenate user input into a raw query string — this is a SQL injection vector.\n\n## Relation loading\n- Prefer `include` over N+1 patterns. If a resolver loads a relation in a loop,\n  refactor to a single query with `include` or use a DataLoader.\n- Do not `include` deeply nested relations more than 2 levels deep in a single query.\n  Flatten with multiple targeted queries and join in application code if needed.\n\n## Type safety\n- All repository functions must return typed Prisma result types or mapped domain types.\n  Never return `any` or plain `object` from a database function.\n- Use `Prisma.validator()` to define reusable select/include shapes that keep return\n  types precise.\n\n## Definition of done\n- `prisma validate` passes.\n- `tsc --noEmit` passes.\n- No `new PrismaClient()` outside `src/lib/prisma.ts`.\n- No `findMany` calls without `take`.\n- Migration files are committed alongside schema changes.\n```\n\n## Por que essas regras\n\n- **Nunca editar o schema sem confirmação** é inegociável. As migrações do Prisma são irreversíveis em produção — uma coluna removida ou uma tabela renomeada sem um plano de migração de dados causa perda de dados. Agentes que são \"prestativos\" executarão alegremente `migrate dev` no momento em que tocarem no schema.\n- **Importação singleton do cliente** evita um dos erros mais comuns em serverless: esgotamento do pool de conexões. Em funções serverless do Next.js, cada avaliação de módulo cria uma nova instância de `PrismaClient` (e um novo pool de conexões) a menos que o padrão singleton seja usado. Agentes que copiam exemplos da documentação do Prisma geralmente ignoram isso.\n\n## Adequado para\n\n- Aplicações Next.js ou Node.js que usam Prisma com PostgreSQL, onde o schema é maduro e a segurança de migrações é crítica.\n\n## Não adequado para\n\n- Projetos novos sem dados ainda, onde você deseja que o agente itere livremente no schema — afrouxe o requisito de aprovação de migração nessa fase."
}