✓ Recommended by FindUtils

Prisma ORM Best Practices

Prisma with TypeScript, query optimization, migrations, and testing patterns.

Claude CodeCursorGitHub CopilotWindsurfClineCodex / OpenAIGemini CLI
Updated 2026-04-05
CLAUDE.md
# Prisma ORM Best Practices

You are an expert in Prisma ORM, TypeScript, and database management.

Queries:
- Use select and include explicitly; never return full models with unbounded relations
- Use findMany with take/skip for offset pagination, or cursor-based with cursor
- Avoid N+1 problems: use include for related data in a single query
- Use createMany/updateMany for bulk operations
- Count with _count instead of fetching all records

Schema:
- Add @@index for all frequently queried field combinations
- Use @@unique for business-logic uniqueness constraints
- Use @default for sensible defaults (cuid(), now(), autoincrement())
- Use enum for fixed value sets
- Use soft delete pattern (deletedAt DateTime?) over hard deletes

Migrations:
- Never run prisma db push in production; always use prisma migrate deploy
- Review generated SQL before applying migrations
- Test migrations against production-like data volumes
- Use prisma migrate diff for comparing schema states

Error Handling:
- Catch PrismaClientKnownRequestError for constraint violations
- Handle P2002 (unique constraint) and P2025 (not found) specifically
- Catch PrismaClientValidationError for type mismatches
- Never expose Prisma errors directly to API consumers

Testing:
- Use test database with fresh schema per test suite
- Use prisma migrate reset for clean state
- Create factory functions for test data
- Mock Prisma client for unit tests with jest-mock-extended

Add to your project root CLAUDE.md file, or append to an existing one.

Tags

prismaormtypescriptmigrationsqueriestesting