Skip to main content
skill Claude Code CX Codex Cursor GitHub Copilot

prisma-expert — Claude Code skill: Prisma ORM and installation

This skill helps inspect Prisma schemas, migrations, and queries. Use it to investigate an error or review database changes before deployment.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add sickn33/agentic-awesome-skills --skill prisma-expert -a claude-code
Open on GitHub

What prisma-expert does

The skill examines Prisma schemas and queries, then suggests fixes for relations, field types, and indexes. For query issues, it covers N+1 patterns and fetching excess data, with examples using include, select, and raw SQL. It also provides guidance for diagnosing migration conflicts and failures.

Its instructions include Prisma CLI checks for schema validation and migration status, plus Prisma Client examples. For dependent writes, it shows nested operations and interactive transactions: an array transaction cannot pass a generated ID from one operation to the next. Before resolving a failed migration, reconcile the actual database state, back it up, and test the changes. Raw SQL optimization and database server configuration fall outside this skill's scope; it recommends handing those issues to another specialist.

What it helps with

  • fix relation definitions and field types in a Prisma schema
  • investigate a migration conflict or failure
  • fetch only needed fields with select
  • replace repeated related-record lookups with an include query

Example prompts for the agent

  • Check `prisma/schema.prisma` for relation and field type errors.
  • Review the migration status and propose a safe way to address the failure.
  • Find the N+1 issue in this Prisma code and select only the required fields.

How to install prisma-expert

1Skills CLI (Vercel)

npx skills add sickn33/agentic-awesome-skills --skill prisma-expert -a claude-code

2Manually: put the files in place

~/.claude/skills/prisma-expert/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/prisma-expert/

From the same set80

The whole set →
docker-expert sickn33 A skill that turns your AI agent into a Docker reviewer for Dockerfiles, multi-stage builds and container security. Useful when images and Compose files need a second look. Claude Code CX Codex Cursor +1 27,200installs typescript-expert sickn33 A skill for TypeScript and JavaScript work: it reads your project setup, fixes type errors and speeds up type checking. Useful once a TS codebase gets big. Claude Code CX Codex Cursor +1 12,600installs browser-automation sickn33 This skill builds browser checks around observed UI state and explicit outcomes. Use it for UI workflows, timing failures, or authorised page-data collection. Claude Code CX Codex Cursor +1 6,700installs nextjs-supabase-auth sickn33 This skill wires Supabase Auth into the Next.js App Router with clients, middleware, OAuth callbacks, and Server Actions. Use it when you need protected routes and session handling. Claude Code CX Codex Cursor +1 6,500installs 3d-web-experience sickn33 Helps build and debug web 3D scenes, product configurators, and portfolios. Covers stack choice, model loading, scroll interaction, and performance checks. Claude Code CX Codex Cursor +1 5,200installs playwright-skill sickn33 Write and run Playwright browser tests directly in Claude Code: responsive design checks, login flows, form submissions, screenshots. Executes locally via Node with a visible browser window. Claude Code CX Codex Cursor +1 3,900installs game-development sickn33 Guides game architecture decisions, platform choices, and core loop structure. Directs the assistant to specialized sub-skills for web, mobile, PC, or VR. Claude Code CX Codex Cursor +1 3,800installs mobile-design sickn33 Reviews and guides iOS, Android, React Native, and Flutter interfaces for touch targets, offline handling, and rendering performance. Claude Code CX Codex Cursor +1 3,700installs

Similar

neon-postgres neondatabase This skill guides agents through Neon Postgres connections, schema changes, branching, and database checks. Use it when working with an existing schema or DATABASE_URL. Claude Code CX Codex Cursor +1 278,200installs wren Canner Connects AI agents to the Wren semantic SQL layer across 22+ databases and SaaS sources. Solves data questions, generates MDL models, and scaffolds GenBI web apps. Claude Code CX Codex Cursor +1 1,500installs break-trace official anthropics The skill traces a reconciliation break to its source entries and states what differs. Use it after gl-recon has classified the break. Claude Code CX Codex Cursor +1 1,200installs k2 cloudflare This skill helps configure Cloudflare K2, produce records from Workers or HTTP, and consume them through subscriptions. Use it when working with durable logs. Claude Code CX Codex Cursor +1 20,100installs basin cloudflare Skill for building and troubleshooting Cloudflare Basin analytics. Stream data into R2 Iceberg tables, manage catalogs, and run distributed SQL queries from your IDE. Claude Code CX Codex Cursor +1 20,000installs google-cloud-storage-bucket-architect official google This skill plans and creates Google Cloud Storage buckets around a workload and the project's security settings. Use it when an app, service, or pipeline needs object storage. Claude Code Gemini CLI CX Codex 2,800installs xlsx official anthropics Creates, reads, edits, and converts spreadsheet files. Use it when the requested deliverable is an Excel workbook or another tabular file. Claude Code Claude.ai 187,223installs google-agents-cli-observability official Google This skill guides you through tracing and monitoring AI agents, including ADK agents. Use it when you need to inspect agent execution or monitor a deployed agent. Claude Code CX Codex Cursor +1 509,900installs

Questions about prisma-expert

How do I install prisma-expert in Claude Code?

Run npx skills add sickn33/agentic-awesome-skills --skill prisma-expert -a claude-code.

What does prisma-expert do?

It examines Prisma schemas, migrations, and Prisma Client queries, then suggests ways to diagnose and fix issues.

What should I check before resolving a failed migration?

Reconcile the actual database state, make a backup, and test the changes. migrate resolve updates migration history; it does not execute missing SQL.

Source text

SKILL.md · MIT
---
name: prisma-expert
description: "You are an expert in Prisma ORM with deep knowledge of schema design, migrations, query optimization, relations modeling, and database operations across PostgreSQL, MySQL, and SQLite."
risk: critical
source: community
date_added: "2026-02-27"
---

# Prisma Expert

You are an expert in Prisma ORM with deep knowledge of schema design, migrations, query optimization, relations modeling, and database operations across PostgreSQL, MySQL, and SQLite.

### When Invoked

### Step 0: Recommend Specialist and Stop
If the issue is specifically about:
- **Raw SQL optimization**: Stop and recommend postgres-expert or mongodb-expert
- **Database server configuration**: Stop and recommend database-expert
- **Connection pooling at infrastructure level**: Stop and recommend devops-expert

### Environment Detection
```bash
# Check Prisma version
npx prisma --version 2>/dev/null || echo "Prisma not installed"

# Check database provider
grep "provider" prisma/schema.prisma 2>/dev/null | head -1

# Check for existing migrations
ls -la prisma/migrations/ 2>/dev/null | head -5

# Check Prisma Client generation status
ls -la node_modules/.prisma/client/ 2>/dev/null | head -3
```

### Apply Strategy
1. Identify the Prisma-specific issue category
2. Check for common anti-patterns in schema or queries
3. Apply progressive fixes (minimal → better → complete)
4. Validate with Prisma CLI and testing

These CLI/client patterns depend on the installed Prisma major and engine/driver adapter. Inspect its help before using migration diff flags or pool URL parameters. Do not let npx fetch an unreviewed CLI for detection. The schema fragment omits Profile and the transaction/version examples require application models and fields. A unique email already supplies an index in the shown providers; do not add redundant indexes without query-plan evidence. Log query timing/shape without sensitive values. Reset destroys data; resolve --applied only records history and does not execute missing SQL, while --rolled-back does not undo database changes. Reconcile actual database state, backup and test before resolving or deploying failed migrations. Array transactions cannot pass a generated ID from one operation into the next; use nested writes or the shown interactive transaction for dependent records.

## Problem Playbooks

### Schema Design
**Common Issues:**
- Incorrect relation definitions causing runtime errors
- Missing indexes for frequently queried fields
- Enum synchronization issues between schema and database
- Field type mismatches

**Diagnosis:**
```bash
# Validate schema
npx prisma validate

# Check for schema drift
npx prisma migrate diff --from-schema-datamodel prisma/schema.prisma --to-schema-datasource prisma/schema.prisma

# Format schema
npx prisma format
```

**Prioritized Fixes:**
1. **Minimal**: Fix relation annotations, add missing `@relation` directives
2. **Better**: Add proper indexes with `@@index`, optimize field types
3. **Complete**: Restructure schema with proper normalization, add composite keys

**Best Practices:**
```prisma
// Good: Explicit relations with clear naming
model User {
  id        String   @id @default(cuid())
  email     String   @unique
  posts     Post[]   @relation("UserPosts")
  profile   Profile? @relation("UserProfile")
  
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  
  @@index([email])
  @@map("users")
}

model Post {
  id       String @id @default(cuid())
  title    String
  author   User   @relation("UserPosts", fields: [authorId], references: [id], onDelete: Cascade)
  authorId String
  
  @@index([authorId])
  @@map("posts")
}
```

**Resources:**
- https://www.prisma.io/docs/concepts/components/prisma-schema
- https://www.prisma.io/docs/concepts/components/prisma-schema/relations

### Migrations
**Common Issues:**
- Migration conflicts in team environments
- Failed migrations leaving database in inconsistent state
- Shadow database issues during development
- Production deployment migration failures

**Diagnosis:**
```bash
# Check migration status
npx prisma migrate status

# View pending migrations
ls -la prisma/migrations/

# Check migration history table
# (use database-specific command)
```

**Prioritized Fixes:**
1. **Minimal**: Reset development database with `prisma migrate reset`
2. **Better**: Manually fix migration SQL, use `prisma migrate resolve`
3. **Complete**: Squash migrations, create baseline for fresh setup

**Safe Migration Workflow:**
```bash
# Development
npx prisma migrate dev --name descriptive_name

# Production (never use migrate dev!)
npx prisma migrate deploy

# If migration fails in production
npx prisma migrate resolve --applied "migration_name"
# or
npx prisma migrate resolve --rolled-back "migration_name"
```

**Resources:**
- https://www.prisma.io/docs/concepts/components/prisma-migrate
- https://www.prisma.io/docs/guides/deployment/deploy-database-changes

### Query Optimization
**Common Issues:**
- N+1 query problems with relations
- Over-fetching data with excessive includes
- Missing select for large models
- Slow queries without proper indexing

**Diagnosis:**
```bash
# Enable query logging
# In schema.prisma or client initialization:
# log: ['query', 'info', 'warn', 'error']
```

```typescript
// Enable query events
const prisma = new PrismaClient({
  log: [
    { emit: 'event', level: 'query' },
  ],
});

prisma.$on('query', (e) => {
  console.log('Query: ' + e.query);
  console.log('Duration: ' + e.duration + 'ms');
});
```

**Prioritized Fixes:**
1. **Minimal**: Add includes for related data to avoid N+1
2. **Better**: Use select to fetch only needed fields
3. **Complete**: Use raw queries for complex aggregations, implement caching

**Optimized Query Patterns:**
```typescript
// BAD: N+1 problem
const users = await prisma.user.findMany();
for (const user of users) {
  const posts = await prisma.post.findMany({ where: { authorId: user.id } });
}

// GOOD: Include relations
const users = await prisma.user.findMany({
  include: { posts: true }
});

// BETTER: Select only needed fields
const users = await prisma.user.findMany({
  select: {
    id: true,
    email: true,
    posts: {
      select: { id: true, title: true }
    }
  }
});

// BEST for complex queries: Use $queryRaw
const result = await prisma.$queryRaw`
  SELECT u.id, u.email, COUNT(p.id) as post_count
  FROM users u
  LEFT JOIN posts p ON p."authorId" = u.id
  GROUP BY u.id
`;
```

**Resources:**
- https://www.prisma.io/docs/guides/performance-and-optimization
- https://www.prisma.io/docs/concepts/components/prisma-client/raw-database-access

### Connection Management
**Common Issues:**
- Connection pool exhaustion
- "Too many connections" errors
- Connection leaks in serverless environments
- Slow initial connections

**Diagnosis:**
```bash
# Check current connections (PostgreSQL)
psql -c "SELECT count(*) FROM pg_stat_activity WHERE datname = 'your_db';"
```

**Prioritized Fixes:**
1. **Minimal**: Configure connection limit in DATABASE_URL
2. **Better**: Implement proper connection lifecycle management
3. **Complete**: Use connection pooler (PgBouncer) for high-traffic apps

**Connection Configuration:**
```typescript
// For serverless (Vercel, AWS Lambda)
import { PrismaClient } from '@prisma/client';

const globalForPrisma = global as unknown as { prisma: PrismaClient };

export const prisma =
  globalForPrisma.prisma ||
  new PrismaClient({
    log: process.env.NODE_ENV === 'development' ? ['query'] : [],
  });

if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;

// Graceful shutdown
process.on('beforeExit', async () => {
  await prisma.$disconnect();
});
```

```env
# Connection URL with pool settings
DATABASE_URL="postgresql://user:pass@host:5432/db?connection_limit=5&pool_timeout=10"
```

**Resources:**
- https://www.prisma.io/docs/guides/performance-and-optimization/connection-management
- https://www.prisma.io/docs/guides/deployment/deployment-guides/deploying-to-vercel

### Transaction Patterns
**Common Issues:**
- Inconsistent data from non-atomic operations
- Deadlocks in concurrent transactions
- Long-running transactions blocking reads
- Nested transaction confusion

**Diagnosis:**
```typescript
// Check for transaction issues
try {
  const result = await prisma.$transaction([...]);
} catch (e) {
  if (e.code === 'P2034') {
    console.log('Transaction conflict detected');
  }
}
```

**Transaction Patterns:**
```typescript
// Sequential operations (auto-transaction)
const [user, profile] = await prisma.$transaction([
  prisma.user.create({ data: userData }),
  prisma.profile.create({ data: profileData }),
]);

// Interactive transaction with manual control
const result = await prisma.$transaction(async (tx) => {
  const user = await tx.user.create({ data: userData });
  
  // Business logic validation
  if (user.email.endsWith('@blocked.com')) {
    throw new Error('Email domain blocked');
  }
  
  const profile = await tx.profile.create({
    data: { ...profileData, userId: user.id }
  });
  
  return { user, profile };
}, {
  maxWait: 5000,  // Wait for transaction slot
  timeout: 10000, // Transaction timeout
  isolationLevel: 'Serializable', // Strictest isolation
});

// Optimistic concurrency control
const updateWithVersion = await prisma.post.update({
  where: { 
    id: postId,
    version: currentVersion  // Only update if version matches
  },
  data: {
    content: newContent,
    version: { increment: 1 }
  }
});
```

**Resources:**
- https://www.prisma.io/docs/concepts/components/prisma-client/transactions

## Code Review Checklist

### Schema Quality
- [ ] All models have appropriate `@id` and primary keys
- [ ] Relations use explicit `@relation` with `fields` and `references`
- [ ] Cascade behaviors defined (`onDelete`, `onUpdate`)
- [ ] Indexes added for frequently queried fields
- [ ] Enums used for fixed value sets
- [ ] `@@map` used for table naming conventions

### Query Patterns
- [ ] No N+1 queries (relations included when needed)
- [ ] `select` used to fetch only required fields
- [ ] Pagination implemented for list queries
- [ ] Raw queries used for complex aggregations
- [ ] Proper error handling for database operations

### Performance
- [ ] Connection pooling configured appropriately
- [ ] Indexes exist for WHERE clause fields
- [ ] Composite indexes for multi-column queries
- [ ] Query logging enabled in development
- [ ] Slow queries identified and optimized

### Migration Safety
- [ ] Migrations tested before production deployment
- [ ] Backward-compatible schema changes (no data loss)
- [ ] Migration scripts reviewed for correctness
- [ ] Rollback strategy documented

## Anti-Patterns to Avoid

1. **Implicit Many-to-Many Overhead**: Always use explicit join tables for complex relationships
2. **Over-Including**: Don't include relations you don't need
3. **Ignoring Connection Limits**: Always configure pool size for your environment
4. **Raw Query Abuse**: Use Prisma queries when possible, raw only for complex cases
5. **Migration in Production Dev Mode**: Never use `migrate dev` in production

## When to Use
This skill is applicable to execute the workflow or actions described in the overview.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.

© sickn33 · MIT · sickn33/agentic-awesome-skills

See also

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor