prisma-cli
Prisma CLI commands reference covering all available commands, options, and usage patterns. Use when running Prisma CLI commands, setting up projects, generating client, running migrations, or managing databases. Triggers on "prisma init", "prisma generate", "prisma migrate", "prisma db", "prisma studio".
Packaged view
This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.
Install command
npx @skill-hub/cli install prisma-skills-prisma-cli
Repository
Skill path: prisma-cli
Prisma CLI commands reference covering all available commands, options, and usage patterns. Use when running Prisma CLI commands, setting up projects, generating client, running migrations, or managing databases. Triggers on "prisma init", "prisma generate", "prisma migrate", "prisma db", "prisma studio".
Open repositoryBest for
Primary workflow: Ship Full Stack.
Technical facets: Full Stack, Backend.
Target audience: everyone.
License: MIT.
Original source
Catalog source: SkillHub Club.
Repository owner: prisma.
This is still a mirrored public skill entry. Review the repository before installing into production workflows.
What it helps with
- Install prisma-cli into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
- Review https://github.com/prisma/skills before adding prisma-cli to shared team environments
- Use prisma-cli for development workflows
Works across
Favorites: 0.
Sub-skills: 0.
Aggregator: No.
Original source / Raw SKILL.md
---
name: prisma-cli
description: Prisma CLI commands reference covering all available commands, options, and usage patterns. Use when running Prisma CLI commands, setting up projects, generating client, running migrations, or managing databases. Triggers on "prisma init", "prisma generate", "prisma migrate", "prisma db", "prisma studio".
license: MIT
metadata:
author: prisma
version: "7.0.0"
---
# Prisma CLI Reference
Complete reference for all Prisma CLI commands. This skill provides guidance on command usage, options, and best practices for Prisma ORM 7.x.
## When to Apply
Reference this skill when:
- Setting up a new Prisma project (`prisma init`)
- Generating Prisma Client (`prisma generate`)
- Running database migrations (`prisma migrate`)
- Managing database state (`prisma db push/pull`)
- Using local development database (`prisma dev`)
- Debugging Prisma issues (`prisma debug`)
## Command Categories
| Category | Commands | Purpose |
|----------|----------|---------|
| Setup | `init` | Bootstrap new Prisma project |
| Generation | `generate` | Generate Prisma Client |
| Validation | `validate`, `format` | Schema validation and formatting |
| Development | `dev` | Local Prisma Postgres for development |
| Database | `db pull`, `db push`, `db seed`, `db execute` | Direct database operations |
| Migrations | `migrate dev`, `migrate deploy`, `migrate reset`, `migrate status`, `migrate diff`, `migrate resolve` | Schema migrations |
| Utility | `studio`, `version`, `debug` | Development tools |
## Quick Reference
### Project Setup
```bash
# Initialize new project (creates prisma/ folder and prisma.config.ts)
prisma init
# Initialize with specific database
prisma init --datasource-provider postgresql
prisma init --datasource-provider mysql
prisma init --datasource-provider sqlite
# Initialize with Prisma Postgres (cloud)
prisma init --db
# Initialize with AI-generated schema
prisma init --prompt "E-commerce app with users, products, orders"
```
### Client Generation
```bash
# Generate Prisma Client
prisma generate
# Watch mode for development
prisma generate --watch
# Generate without engine (for Accelerate/edge)
prisma generate --no-engine
# Generate specific generator only
prisma generate --generator client
```
### Bun Runtime
When using Bun, always add the `--bun` flag so Prisma runs with the Bun runtime (otherwise it falls back to Node.js because of the CLI shebang):
```bash
bunx --bun prisma init
bunx --bun prisma generate
```
### Local Development Database
```bash
# Start local Prisma Postgres
prisma dev
# Start with specific name
prisma dev --name myproject
# Start in background (detached)
prisma dev --detach
# List all local instances
prisma dev ls
# Stop instance
prisma dev stop myproject
# Remove instance data
prisma dev rm myproject
```
### Database Operations
```bash
# Pull schema from existing database
prisma db pull
# Push schema to database (no migrations)
prisma db push
# Seed database
prisma db seed
# Execute raw SQL
prisma db execute --file ./script.sql
```
### Migrations (Development)
```bash
# Create and apply migration
prisma migrate dev
# Create migration with name
prisma migrate dev --name add_users_table
# Create migration without applying
prisma migrate dev --create-only
# Reset database and apply all migrations
prisma migrate reset
```
### Migrations (Production)
```bash
# Apply pending migrations (CI/CD)
prisma migrate deploy
# Check migration status
prisma migrate status
# Compare schemas and generate diff
prisma migrate diff --from-config-datasource --to-schema schema.prisma --script
```
### Utility Commands
```bash
# Open Prisma Studio (database GUI)
prisma studio
# Show version info
prisma version
prisma -v
# Debug information
prisma debug
# Validate schema
prisma validate
# Format schema
prisma format
```
## Prisma 7 Changes
### New Configuration File
Prisma 7 uses `prisma.config.ts` for CLI configuration:
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts',
},
datasource: {
url: env('DATABASE_URL'),
},
})
```
### Removed Flags
- `--skip-generate` removed from `migrate dev` and `db push`
- `--skip-seed` removed from `migrate dev`
- `--schema` and `--url` removed from `db execute`
- Run `prisma generate` explicitly after migrations
### Environment Variables
Environment variables are no longer auto-loaded. Use `dotenv`:
```typescript
// prisma.config.ts
import 'dotenv/config'
```
## Rule Files
See individual rule files for detailed command documentation:
```
rules/init.md - Project initialization
rules/generate.md - Client generation
rules/dev.md - Local development database
rules/db-pull.md - Database introspection
rules/db-push.md - Schema push
rules/db-seed.md - Database seeding
rules/db-execute.md - Raw SQL execution
rules/migrate-dev.md - Development migrations
rules/migrate-deploy.md - Production migrations
rules/migrate-reset.md - Database reset
rules/migrate-status.md - Migration status
rules/migrate-resolve.md - Migration resolution
rules/migrate-diff.md - Schema diffing
rules/studio.md - Database GUI
rules/validate.md - Schema validation
rules/format.md - Schema formatting
rules/debug.md - Debug info
```
---
## Referenced Files
> The following files are referenced in this skill and included for context.
### rules/init.md
```markdown
# prisma init
Bootstraps a fresh Prisma ORM project in the current directory.
## Command
```bash
prisma init [options]
```
## Bun Runtime
If you're using Bun, run Prisma with `bunx --bun` so it doesn't fall back to Node.js:
```bash
bunx --bun prisma init
```
## What It Creates
- `prisma/schema.prisma` - Your Prisma schema file
- `prisma.config.ts` - TypeScript configuration for Prisma CLI
- `.env` - Environment variables (DATABASE_URL)
- `.gitignore` - Ignores node_modules, .env, and generated files
## Options
| Option | Description | Default |
|--------|-------------|---------|
| `--datasource-provider` | Database provider: `postgresql`, `mysql`, `sqlite`, `sqlserver`, `mongodb`, `cockroachdb` | `postgresql` |
| `--db` | Provisions a fully managed Prisma Postgres database on the Prisma Data Platform | - |
| `--url` | Define a custom datasource url | - |
| `--generator-provider` | Define the generator provider to use | `prisma-client` |
| `--output` | Define Prisma Client generator output path to use | - |
| `--preview-feature` | Define a preview feature to use | - |
| `--with-model` | Add example model to created schema file | - |
## Examples
### Basic initialization
```bash
prisma init
```
Creates a PostgreSQL project setup.
### SQLite project
```bash
prisma init --datasource-provider sqlite
```
### MySQL with custom URL
```bash
prisma init --datasource-provider mysql --url "mysql://user:password@localhost:3306/mydb"
```
### Prisma Postgres (cloud)
```bash
prisma init --db
```
Opens browser for authentication, creates cloud database instance.
### AI-generated schema
```bash
prisma init --prompt "Blog with users, posts, comments, and tags"
```
Generates schema based on description and deploys to Prisma Postgres.
### With preview features
```bash
prisma init --preview-feature relationJoins --preview-feature fullTextSearch
```
## Generated Schema (v7)
```prisma
generator client {
provider = "prisma-client"
output = "../generated"
}
datasource db {
provider = "postgresql"
}
```
## Generated Config (v7)
```typescript
// prisma.config.ts
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Next Steps After Init
1. Configure `DATABASE_URL` in `prisma.config.ts` or `.env`
2. Define your models in `prisma/schema.prisma`
3. Run `prisma dev` for local development or connect to remote DB
4. Run `prisma migrate dev` to create migrations
5. Run `prisma generate` to generate Prisma Client
```
### rules/generate.md
```markdown
# prisma generate
Generates assets based on the generator blocks in your Prisma schema, most commonly Prisma Client.
## Command
```bash
prisma generate [options]
```
## Bun Runtime
If you're using Bun, run Prisma with `bunx --bun` so it doesn't fall back to Node.js:
```bash
bunx --bun prisma generate
```
## What It Does
1. Reads your `schema.prisma` file
2. Generates a customized Prisma Client based on your models
3. Outputs to the directory specified in the generator block
## Options
| Option | Description |
|--------|-------------|
| `--schema` | Custom path to your Prisma schema |
| `--config` | Custom path to your Prisma config file |
| `--sql` | Generate typed sql module |
| `--watch` | Watch the Prisma schema and rerun after a change |
| `--generator` | Generator to use (may be provided multiple times) |
| `--no-hints` | Hides the hint messages but still outputs errors and warnings |
| `--require-models` | Do not allow generating a client without models |
## Examples
### Basic generation
```bash
prisma generate
```
### Watch mode (development)
```bash
prisma generate --watch
```
Auto-regenerates when `schema.prisma` changes.
### Specific generator
```bash
prisma generate --generator client
```
### Multiple generators
```bash
prisma generate --generator client --generator zod_schemas
```
### Typed SQL generation
```bash
prisma generate --sql
```
## Schema Configuration (v7)
```prisma
generator client {
provider = "prisma-client"
output = "../generated"
}
```
### Key v7 Changes
- Provider must be `prisma-client`
- `output` is now **required** - client no longer generates to `node_modules`
- Update imports after generating:
```typescript
// Before (v6)
import { PrismaClient } from '@prisma/client'
// After (v7)
import { PrismaClient } from '../generated/client'
```
## Common Patterns
### After schema changes
```bash
prisma migrate dev --name my_migration
prisma generate
```
Note: In v7, `migrate dev` no longer auto-runs `generate`.
### CI/CD pipeline
```bash
prisma generate
```
Run before building your application.
### Multiple generators
```prisma
generator client {
provider = "prisma-client"
output = "../generated"
}
generator zod {
provider = "zod-prisma-types"
output = "../generated/zod"
}
```
```bash
prisma generate # Runs all generators
```
## Output Structure
After running `prisma generate`, your output directory contains:
```
generated/
├── client.ts
├── models/
├── enums.ts
└── ...
```
Import the client:
```typescript
import { PrismaClient, Prisma } from '../generated/client'
```
```
### rules/dev.md
```markdown
# prisma dev
Starts a local Prisma Postgres database for development. Provides a PostgreSQL-compatible database that runs entirely on your machine.
## Command
```bash
prisma dev [options]
```
## What It Does
- Starts a local PostgreSQL-compatible database
- Runs in your terminal or as a background process
- Perfect for development and testing
- Easy migration to Prisma Postgres cloud in production
## Options
| Option | Description | Default |
|--------|-------------|---------|
| `--name` / `-n` | Name for the database instance | `default` |
| `--port` / `-p` | HTTP server port | `51213` |
| `--db-port` / `-P` | Database server port | `51214` |
| `--shadow-db-port` | Shadow database port (for migrations) | `51215` |
| `--detach` / `-d` | Run in background | `false` |
| `--debug` | Enable debug logging | `false` |
## Examples
### Start local database
```bash
prisma dev
```
Interactive mode with keyboard shortcuts:
- `q` - Quit
- `h` - Show HTTP URL
- `t` - Show TCP URLs
### Named instance
```bash
prisma dev --name myproject
```
Useful for multiple projects.
### Background mode
```bash
prisma dev --detach
```
Frees your terminal for other commands.
### Custom ports
```bash
prisma dev --port 5000 --db-port 5432
```
## Instance Management
### List all instances
```bash
prisma dev ls
```
Shows all local Prisma Postgres instances with status.
### Start existing instance
```bash
prisma dev start myproject
```
Starts a previously created instance in background.
### Stop instance
```bash
prisma dev stop myproject
```
### Stop with glob pattern
```bash
prisma dev stop "myproject*"
```
Stops all instances matching pattern.
### Remove instance
```bash
prisma dev rm myproject
```
Removes instance data from filesystem.
### Force remove (stops first)
```bash
prisma dev rm myproject --force
```
## Configuration
Configure your `prisma.config.ts` to use local Prisma Postgres:
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
// Local Prisma Postgres URL (from prisma dev output)
url: env('DATABASE_URL'),
},
})
```
## Workflow
1. Start local database:
```bash
prisma dev
```
2. In another terminal, run migrations:
```bash
prisma migrate dev
```
3. Generate client:
```bash
prisma generate
```
4. Run your application
## Production Migration
When ready for production, switch to Prisma Postgres cloud:
```bash
prisma init --db
```
Update your `DATABASE_URL` to the cloud connection string.
```
### rules/db-pull.md
```markdown
# prisma db pull
Introspects an existing database and updates your Prisma schema to reflect its structure.
## Command
```bash
prisma db pull [options]
```
## What It Does
- Connects to your database
- Reads the database schema (tables, columns, relations, indexes)
- Updates `schema.prisma` with corresponding Prisma models
- For MongoDB, samples data to infer schema
## Options
| Option | Description |
|--------|-------------|
| `--force` | Ignore current Prisma schema file |
| `--print` | Print the introspected Prisma schema to stdout |
| `--schema` | Custom path to your Prisma schema |
| `--config` | Custom path to your Prisma config file |
| `--url` | Override the datasource URL from the Prisma config file |
| `--composite-type-depth` | Specify the depth for introspecting composite types (default: -1 for infinite, 0 = off) |
| `--schemas` | Specify the database schemas to introspect |
| `--local-d1` | Generate a Prisma schema from a local Cloudflare D1 database |
## Examples
### Basic introspection
```bash
prisma db pull
```
### Preview without writing
```bash
prisma db pull --print
```
Outputs schema to terminal for review.
### Force overwrite
```bash
prisma db pull --force
```
Replaces schema file, losing any manual customizations.
## Prerequisites
Configure database connection in `prisma.config.ts`:
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Workflow
### Starting from existing database
1. Initialize Prisma:
```bash
prisma init
```
2. Configure database URL
3. Pull schema:
```bash
prisma db pull
```
4. Review and customize generated schema
5. Generate client:
```bash
prisma generate
```
### Syncing changes from database
When database changes are made outside Prisma:
```bash
prisma db pull
prisma generate
```
## Generated Schema Example
Database tables become Prisma models:
```sql
-- Database tables
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(100)
);
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author_id INTEGER REFERENCES users(id)
);
```
Becomes:
```prisma
model users {
id Int @id @default(autoincrement())
email String @unique @db.VarChar(255)
name String? @db.VarChar(100)
posts posts[]
}
model posts {
id Int @id @default(autoincrement())
title String @db.VarChar(255)
author_id Int?
users users? @relation(fields: [author_id], references: [id])
}
```
## Post-Introspection Cleanup
After `db pull`, consider:
1. **Rename models** to PascalCase:
```prisma
model User { // Was: users
@@map("users")
}
```
2. **Rename fields** to camelCase:
```prisma
authorId Int? @map("author_id")
```
3. **Add relation names** for clarity:
```prisma
author User? @relation("PostAuthor", fields: [authorId], references: [id])
```
4. **Add documentation**:
```prisma
/// User account information
model User {
/// Primary email for authentication
email String @unique
}
```
## MongoDB Introspection
For MongoDB, `db pull` samples documents to infer schema:
```bash
prisma db pull
```
May require manual refinement since MongoDB is schemaless.
## Warning
`db pull` overwrites your schema file. Always:
- Commit current schema before pulling
- Use `--print` to preview first
- Backup customizations you want to keep
```
### rules/db-push.md
```markdown
# prisma db push
Pushes schema changes directly to database without creating migrations. Ideal for prototyping.
## Command
```bash
prisma db push [options]
```
## What It Does
- Syncs your Prisma schema to the database
- Creates database if it doesn't exist
- Does NOT create migration files
- Does NOT track migration history
## Options
| Option | Description |
|--------|-------------|
| `--force-reset` | Force a reset of the database before push |
| `--accept-data-loss` | Ignore data loss warnings |
| `--schema` | Custom path to your Prisma schema |
| `--config` | Custom path to your Prisma config file |
| `--url` | Override the datasource URL from the Prisma config file |
### Removed in v7
- `--skip-generate` - Run `prisma generate` explicitly
## Examples
### Basic push
```bash
prisma db push
```
### Accept data loss
```bash
prisma db push --accept-data-loss
```
Required when changes would delete data (dropping columns, etc.)
### Force reset
```bash
prisma db push --force-reset
```
Completely resets database and applies schema.
### Full workflow (v7)
```bash
prisma db push
prisma generate # Must run explicitly in v7
```
## When to Use
- **Prototyping** - Rapid schema iteration
- **Local development** - Quick schema changes
- **MongoDB** - Primary workflow (migrations not supported)
- **Testing** - Setting up test databases
## When NOT to Use
- **Production** - Use `migrate deploy`
- **Team collaboration** - Use migrations for trackable changes
- **When you need rollback** - Migrations provide history
## Comparison with migrate dev
| Feature | db push | migrate dev |
|---------|---------|-------------|
| Creates migration files | No | Yes |
| Tracks history | No | Yes |
| Requires shadow database | No | Yes |
| Speed | Faster | Slower |
| Rollback capability | No | Yes |
| Best for | Prototyping | Development |
## MongoDB Workflow
MongoDB doesn't support migrations. Use `db push` exclusively:
```bash
# Schema changes for MongoDB
prisma db push
prisma generate
```
## Common Patterns
### Prototyping workflow
```bash
# Make schema changes
# ...
# Push to database
prisma db push
# Generate client
prisma generate
# Test your changes
# Repeat as needed
```
### Reset and start fresh
```bash
prisma db push --force-reset
prisma db seed
```
### Handling conflicts
If `db push` can't apply changes safely:
```
Error: The following changes cannot be applied:
- Removing field `email` would cause data loss
Use --accept-data-loss to proceed
```
Decide whether data loss is acceptable, then:
```bash
prisma db push --accept-data-loss
```
## Transition to Migrations
When ready for production, switch to migrations:
```bash
# Create baseline migration from current schema
prisma migrate dev --name init
```
Then use `migrate dev` for future changes.
```
### rules/db-seed.md
```markdown
# prisma db seed
Runs your database seed script to populate data.
## Command
```bash
prisma db seed [options]
```
## What It Does
- Executes your configured seed script
- Populates database with initial/test data
- Runs independently (not auto-run by migrations in v7)
## Options
| Option | Description |
|--------|-------------|
| `--config` | Custom path to your Prisma config file |
| `--` | Pass custom arguments to seed script |
## Configuration
Configure seed script in `prisma.config.ts`:
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts', // Your seed command
},
datasource: {
url: env('DATABASE_URL'),
},
})
```
### Common seed commands
```typescript
// TypeScript with tsx
seed: 'tsx prisma/seed.ts'
// TypeScript with ts-node
seed: 'ts-node prisma/seed.ts'
// JavaScript
seed: 'node prisma/seed.js'
```
## Seed Script Example
```typescript
// prisma/seed.ts
import { PrismaClient } from '../generated/client'
const prisma = new PrismaClient()
async function main() {
// Create users
const alice = await prisma.user.upsert({
where: { email: '[email protected]' },
update: {},
create: {
email: '[email protected]',
name: 'Alice',
posts: {
create: {
title: 'Hello World',
published: true,
},
},
},
})
const bob = await prisma.user.upsert({
where: { email: '[email protected]' },
update: {},
create: {
email: '[email protected]',
name: 'Bob',
},
})
console.log({ alice, bob })
}
main()
.then(async () => {
await prisma.$disconnect()
})
.catch(async (e) => {
console.error(e)
await prisma.$disconnect()
process.exit(1)
})
```
## Examples
### Run seed
```bash
prisma db seed
```
### With custom arguments
```bash
prisma db seed -- --environment development
```
Arguments after `--` are passed to your seed script.
## v7 Changes
In Prisma 7, seeding is NOT automatic after migrations:
```bash
# v7 workflow
prisma migrate dev --name init
prisma generate
prisma db seed # Must run explicitly
```
Previously (v6), `migrate dev` and `migrate reset` auto-ran seeds.
## Idempotent Seeding
Use `upsert` to make seeds re-runnable:
```typescript
// Good: Can run multiple times
await prisma.user.upsert({
where: { email: '[email protected]' },
update: {}, // Don't change existing
create: { email: '[email protected]', name: 'Alice' },
})
// Bad: Fails on second run
await prisma.user.create({
data: { email: '[email protected]', name: 'Alice' },
})
```
## Common Patterns
### Development reset
```bash
prisma migrate reset --force
prisma db seed
```
### Conditional seeding
```typescript
// prisma/seed.ts
const count = await prisma.user.count()
if (count === 0) {
// Only seed if empty
await seedUsers()
}
```
### Environment-specific seeds
```typescript
// prisma/seed.ts
const env = process.env.NODE_ENV || 'development'
if (env === 'development') {
await seedDevData()
} else if (env === 'test') {
await seedTestData()
}
```
## Best Practices
1. Use `upsert` for idempotent seeds
2. Keep seeds focused and minimal
3. Use realistic but fake data
4. Document required seed data
5. Version control your seed scripts
```
### rules/db-execute.md
```markdown
# prisma db execute
Execute native commands (SQL) to your database.
## Command
```bash
prisma db execute [options]
```
## What It Does
- Connects to your database using the configured datasource
- Executes a script provided via file (`--file`) or stdin (`--stdin`)
- Useful for running raw SQL, maintenance tasks, or applying diffs from `migrate diff`
- Not supported on MongoDB
## Options
| Option | Description |
|--------|-------------|
| `--file` | Path to a file containing the script to execute |
| `--stdin` | Use terminal standard input as the script |
| `--url` | Override the datasource URL from the Prisma config file |
| `--config` | Custom path to your Prisma config file |
## Examples
### Execute from file
```bash
prisma db execute --file ./script.sql
```
### Execute from stdin
```bash
echo "TRUNCATE TABLE User;" | prisma db execute --stdin
```
### Execute `migrate diff` output
Pipe the output of `migrate diff` directly to the database:
```bash
prisma migrate diff \
--from-empty \
--to-schema-datamodel prisma/schema.prisma \
--script \
| prisma db execute --stdin
```
## Configuration
Uses `datasource` from `prisma.config.ts`:
```typescript
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Use Cases
- **Manual Migrations**: Applying raw SQL changes
- **Data Maintenance**: Truncating tables, cleaning up data
- **Schema Synchronization**: Applying `migrate diff` scripts
- **Debugging**: Running test queries (though typically not for fetching data)
## Limitations
- **No Data Return**: The command reports success/failure, not query results (rows). Use Prisma Client or `prisma studio` to view data.
- **SQL Only**: Primarily for SQL databases.
```
### rules/migrate-dev.md
```markdown
# prisma migrate dev
Creates and applies migrations during development. Requires a shadow database.
## Command
```bash
prisma migrate dev [options]
```
## What It Does
1. Runs existing migrations in shadow database to detect drift
2. Applies any pending migrations
3. Generates new migration from schema changes
4. Applies new migration to development database
5. Updates `_prisma_migrations` table
## Options
| Option | Description |
|--------|-------------|
| `--name` / `-n` | Name the migration |
| `--create-only` | Create a new migration but do not apply it |
| `--schema` | Custom path to your Prisma schema |
| `--config` | Custom path to your Prisma config file |
| `--url` | Override the datasource URL from the Prisma config file |
### Removed in v7
- `--skip-generate` - Run `prisma generate` explicitly
- `--skip-seed` - Run `prisma db seed` explicitly
## Examples
### Create and apply migration
```bash
prisma migrate dev
```
Prompts for migration name if schema changed.
### Named migration
```bash
prisma migrate dev --name add_users_table
```
### Create without applying
```bash
prisma migrate dev --create-only
```
Useful for reviewing migration SQL before applying.
### Full workflow (v7)
```bash
prisma migrate dev --name my_migration
prisma generate # Must run explicitly in v7
prisma db seed # Must run explicitly in v7
```
## Migration Files
Created in `prisma/migrations/`:
```
prisma/migrations/
├── 20240115120000_add_users_table/
│ └── migration.sql
├── 20240116090000_add_posts/
│ └── migration.sql
└── migration_lock.toml
```
## Schema Drift Detection
If `migrate dev` detects drift (manual database changes or edited migrations), it prompts to reset:
```
Drift detected: Your database schema is not in sync.
Do you want to reset your database? All data will be lost.
```
## When to Use
- Local development
- Adding new models/fields
- Changing relations
- Creating indexes
## When NOT to Use
- Production deployments (use `migrate deploy`)
- CI/CD pipelines (use `migrate deploy`)
- MongoDB (use `db push` instead)
## Common Patterns
### After schema changes
```prisma
// schema.prisma - Add new field
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
createdAt DateTime @default(now()) // New field
}
```
```bash
prisma migrate dev --name add_created_at
```
### Handling data loss warnings
When a migration would cause data loss:
```bash
prisma migrate dev --name remove_field
# Warning: You are about to delete data...
# Accept with: --accept-data-loss
```
## Shadow Database
`migrate dev` requires a shadow database for drift detection. Configure in `prisma.config.ts`:
```typescript
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
shadowDatabaseUrl: env('SHADOW_DATABASE_URL'),
},
})
```
For local Prisma Postgres (`prisma dev`), shadow database is handled automatically.
```
### rules/migrate-deploy.md
```markdown
# prisma migrate deploy
Applies pending migrations in production/staging environments.
## Command
```bash
prisma migrate deploy
```
## What It Does
- Applies all pending migrations from `prisma/migrations/`
- Updates `_prisma_migrations` table
- Does NOT generate new migrations
- Does NOT run seed scripts
- Safe for CI/CD and production
## Options
| Option | Description |
|--------|-------------|
| `--schema` | Custom path to your Prisma schema |
| `--config` | Custom path to your Prisma config file |
## When to Use
- Production deployments
- Staging environments
- CI/CD pipelines
- Any non-development environment
## Examples
### Basic deployment
```bash
prisma migrate deploy
```
### In CI/CD pipeline
```yaml
# GitHub Actions example
- name: Apply migrations
run: npx prisma migrate deploy
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
```
### Docker deployment
```dockerfile
# Run migrations before starting app
CMD npx prisma migrate deploy && node dist/index.js
```
## Comparison with migrate dev
| Feature | migrate dev | migrate deploy |
|---------|-------------|----------------|
| Creates migrations | Yes | No |
| Applies migrations | Yes | Yes |
| Detects drift | Yes | No |
| Prompts for input | Yes | No |
| Uses shadow database | Yes | No |
| Safe for production | No | Yes |
| Resets on issues | Prompts | Fails |
## Production Workflow
1. **Development**: Create migrations locally
```bash
prisma migrate dev --name add_feature
```
2. **Commit**: Include migration files in version control
```bash
git add prisma/migrations
git commit -m "Add feature migration"
```
3. **Deploy**: Apply in production
```bash
prisma migrate deploy
```
## Error Handling
### Failed migration
If a migration fails, `migrate deploy` exits with error. The failed migration is marked as failed in `_prisma_migrations`.
To fix:
1. Resolve the issue (fix SQL, database state, etc.)
2. Mark as resolved: `prisma migrate resolve --applied <migration_name>`
3. Re-run: `prisma migrate deploy`
### Check status first
```bash
prisma migrate status
```
Shows pending and applied migrations before deploying.
## Configuration
Ensure `prisma.config.ts` has the production database URL:
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Best Practices
1. Always run `migrate status` before `migrate deploy` in CI
2. Have a rollback plan (backup before migrations)
3. Test migrations in staging first
4. Never use `migrate dev` in production
```
### rules/migrate-reset.md
```markdown
# prisma migrate reset
Resets your database and re-applies all migrations.
## Command
```bash
prisma migrate reset [options]
```
## What It Does
1. **Drops** the database (if possible) or deletes all data/tables
2. **Re-creates** the database
3. **Applies** all migrations from `prisma/migrations/`
4. **Runs** the seed script (if configured)
**Warning: All data will be lost.**
## Options
| Option | Description |
|--------|-------------|
| `--force` / `-f` | Skip confirmation prompt |
| `--schema` | Path to schema file |
| `--config` | Custom path to your Prisma config file |
## Examples
### Basic reset
```bash
prisma migrate reset
```
Prompts for confirmation in interactive terminals.
### Force reset (CI/Automation)
```bash
prisma migrate reset --force
```
### With custom schema
```bash
prisma migrate reset --schema=./custom/schema.prisma
```
## When to Use
- **Development**: When you want a fresh start
- **Testing**: Resetting test database before suites
- **Drift Recovery**: When the database is out of sync and you can't migrate
## Behavior in v7
- In v6, `migrate reset` automatically ran `prisma generate`.
- In v7, you may need to run `prisma generate` separately if you want to update the client, though `reset` focuses on the database state.
- Seed script IS run by default after reset.
## Configuration
Configure seed script in `prisma.config.ts` to run it automatically after reset:
```typescript
export default defineConfig({
migrations: {
seed: 'tsx prisma/seed.ts',
},
})
```
```
### rules/migrate-status.md
```markdown
# prisma migrate status
Checks the status of your database migrations.
## Command
```bash
prisma migrate status [options]
```
## What It Does
- Connects to the database
- Checks the `_prisma_migrations` table
- Compares applied migrations with local migration files
- Reports:
- **Status**: Database is up-to-date or behind
- **Unapplied migrations**: Count of pending migrations
- **Missing migrations**: Migrations present in DB but missing locally
- **Failed migrations**: Any migrations that failed to apply
## Options
| Option | Description |
|--------|-------------|
| `--schema` | Path to schema file |
| `--config` | Custom path to your Prisma config file |
## Examples
### Check status
```bash
prisma migrate status
```
Output example (Up to date):
```
Database schema is up to date!
```
Output example (Pending):
```
Following migration have not yet been applied:
20240115120000_add_user
To apply migrations in development, run:
prisma migrate dev
To apply migrations in production, run:
prisma migrate deploy
```
## When to Use
- **Debugging**: Why is `migrate dev` complaining about drift?
- **CI/CD**: Verify database state before deploying
- **Production**: Check if migrations are needed (`migrate deploy`) or if a deployment failed
## Exit Codes
- `0`: Success (may have pending migrations, but command ran successfully)
- `1`: Error
To check for pending migrations programmatically, you might need to parse the output or use `migrate diff` with exit code flags.
```
### rules/migrate-resolve.md
```markdown
# prisma migrate resolve
Resolves issues with database migrations, such as failed migrations or baselining.
## Command
```bash
prisma migrate resolve [options]
```
## What It Does
Updates the `_prisma_migrations` table to manually change the state of a migration. This is a recovery tool.
## Options
You must provide exactly one of `--applied` or `--rolled-back`.
| Option | Description |
|--------|-------------|
| `--applied <name>` | Mark a migration as **applied** (success) |
| `--rolled-back <name>` | Mark a migration as **rolled back** (ignored/failed) |
| `--schema` | Path to schema file |
| `--config` | Custom path to your Prisma config file |
## Examples
### Mark as Applied (Baselining)
If you have existing tables and want to initialize migrations without running the SQL:
```bash
prisma migrate resolve --applied 20240101000000_initial_migration
```
This tells Prisma "Assume this migration has already run".
### Mark as Rolled Back (Fixing Failures)
If a migration failed (e.g., syntax error) and you fixed the SQL or want to retry:
```bash
prisma migrate resolve --rolled-back 20240115120000_failed_migration
```
This tells Prisma "Forget this migration run, let me try applying it again".
## Use Cases
1. **Baselining**: Adopting Prisma Migrate on an existing production database.
2. **Failed Migrations**: Recovering from a failed `migrate deploy` in production.
3. **Hotfixes**: reconciling manual database changes (rare).
## References
- [Baselining](https://www.prisma.io/docs/guides/database/developing-with-prisma-migrate/baselining)
- [Troubleshooting](https://www.prisma.io/docs/guides/database/production-troubleshooting)
```
### rules/migrate-diff.md
```markdown
# prisma migrate diff
Compares database schemas and generates diffs (SQL or summary).
## Command
```bash
prisma migrate diff [options]
```
## What It Does
- Compares two sources (`--from-...` and `--to-...`)
- Sources can be:
- Empty (`empty`)
- Schema file (`schema`)
- Migrations directory (`migrations`)
- Database URL (`url`) or Configured Datasource (`config-datasource`)
- Outputs the difference:
- Human-readable summary (default)
- SQL script (`--script`)
## Options
| Option | Description |
|--------|-------------|
| `--script` | Render SQL script to stdout |
| `--exit-code` | Exit 2 if changes detected, 0 if empty, 1 if error |
| `--config` | Custom path to your Prisma config file |
### Sources (Must provide one `from` and one `to`)
- `--from-empty`, `--to-empty`
- `--from-schema <path>`, `--to-schema <path>`
- `--from-migrations <path>`, `--to-migrations <path>`
- `--from-url <url>`, `--to-url <url>`
- `--from-config-datasource`, `--to-config-datasource` (uses `prisma.config.ts`)
## Examples
### Generate SQL for a schema change
Compare current production DB to your local schema:
```bash
prisma migrate diff \
--from-url "$PROD_DB_URL" \
--to-schema ./prisma/schema.prisma \
--script
```
### Review pending migrations
Compare database state to migrations directory:
```bash
prisma migrate diff \
--from-config-datasource \
--to-migrations ./prisma/migrations
```
### Create baseline migration
Compare empty state to current schema:
```bash
prisma migrate diff \
--from-empty \
--to-schema ./prisma/schema.prisma \
--script > prisma/migrations/0_init/migration.sql
```
### Check for drift (CI)
Check if database matches schema:
```bash
prisma migrate diff \
--from-config-datasource \
--to-schema ./prisma/schema.prisma \
--exit-code
```
## Use Cases
- **Forward-generating migrations**: Creating SQL without `migrate dev`.
- **Drift detection**: Checking if DB is in sync.
- **Baselining**: Creating initial migration from existing DB.
- **Debugging**: Understanding what `migrate dev` would do.
```
### rules/studio.md
```markdown
# prisma studio
Opens a visual database browser for viewing and editing data.
## Command
```bash
prisma studio [options]
```
## What It Does
- Starts a web-based database GUI
- View all your models and records
- Create, update, and delete records
- Filter and sort data
- Navigate relations
## Options
| Option | Description | Default |
|--------|-------------|---------|
| `--port` / `-p` | Port to start Studio on | `5555` |
| `--browser` / `-b` | Browser to open Studio in | System default |
| `--config` | Custom path to your Prisma config file | - |
| `--url` | Database connection string (overrides the one in your Prisma config) | - |
## Examples
### Open Studio
```bash
prisma studio
```
Opens at http://localhost:5555
### Custom port
```bash
prisma studio --port 3000
```
### Specific browser
```bash
prisma studio --browser firefox
```
### Don't open browser
```bash
BROWSER=none prisma studio
```
Useful for remote servers.
## Features
### View Records
- See all records in table format
- Pagination for large datasets
- Column sorting
### Filter Data
- Filter by any field
- Multiple conditions
- Relation filtering
### Edit Records
- Click to edit inline
- Add new records
- Delete records (with confirmation)
### Navigate Relations
- Click relations to view related records
- See counts of related items
- Follow relation links
## Use Cases
- **Development**: Quick data inspection
- **Debugging**: Check data state
- **Testing**: Verify seed data
- **Demo**: Show data to stakeholders
## Limitations
- Development tool only
- Not for production use
- Limited to configured database
- No advanced queries (use Prisma Client for that)
## Common Workflow
1. Run migrations:
```bash
prisma migrate dev
```
2. Seed data:
```bash
prisma db seed
```
3. Open Studio to verify:
```bash
prisma studio
```
4. Make manual edits if needed
## Security Note
Studio provides direct database access. Only run on:
- Local development machines
- Secure internal networks
- Never expose publicly
```
### rules/validate.md
```markdown
# prisma validate
Validates your Prisma schema file.
## Command
```bash
prisma validate [options]
```
## What It Does
- Parses the `schema.prisma` file
- Checks for syntax errors
- Validates model definitions, relations, and types
- Reports any errors or warnings without generating code
## Options
| Option | Description |
|--------|-------------|
| `--schema` | Path to schema file |
| `--config` | Custom path to your Prisma config file |
## Examples
### Validate default schema
```bash
prisma validate
```
### Validate specific schema
```bash
prisma validate --schema=./custom/schema.prisma
```
### Use in CI
Run `validate` in your CI pipeline to catch schema errors early:
```yaml
- name: Validate Schema
run: npx prisma validate
```
## Common Errors
- Missing `@relation` fields
- Invalid types
- Duplicate model names
- Syntax errors (missing braces, etc.)
```
### rules/format.md
```markdown
# prisma format
Formats your Prisma schema file.
## Command
```bash
prisma format [options]
```
## What It Does
- Fixes formatting (indentation, spacing)
- Adds missing back-relations (e.g., adds the other side of a relation)
- Adds missing relation arguments (e.g., `fields`, `references`)
- Sorts fields and attributes (opinionated)
## Options
| Option | Description |
|--------|-------------|
| `--schema` | Path to schema file |
| `--config` | Custom path to your Prisma config file |
## Examples
### Format default schema
```bash
prisma format
```
### Format specific schema
```bash
prisma format --schema=./custom/schema.prisma
```
## Behavior
`prisma format` modifies the file in place. It is equivalent to "Prettier for Prisma schemas" but also has semantic understanding to fix/add missing schema definitions.
## Use in Editor
Most Prisma editor extensions (VS Code, WebStorm) run `prisma format` automatically on save. This command is useful for:
- CI pipelines (check formatting)
- CLI-based workflows
- Fixing large schema refactors
```
### rules/debug.md
```markdown
# prisma debug
Prints information helpful for debugging and bug reports.
## Command
```bash
prisma debug [options]
```
## What It Does
Outputs details about your Prisma environment, including:
- Prisma CLI version
- Prisma Client version (if installed)
- Engine binaries (Query Engine, Migration Engine, etc.)
- Platform information (OS, Architecture)
- Node.js version
- Configured datasource provider
## Options
| Option | Description |
|--------|-------------|
| `--schema` | Path to schema file |
| `--config` | Custom path to your Prisma config file |
## Example Output
```
prisma : 7.3.0
@prisma/client : 7.3.0
Operating System : darwin
Architecture : arm64
Node.js : v20.10.0
TypeScript : 5.3.3
Query Compiler : enabled
PSL : ...
Schema Engine : ...
```
## When to Use
- **Troubleshooting**: Checking version mismatches
- **Reporting Issues**: Including environment info in GitHub issues
- **Verifying Installation**: Ensuring correct binaries are downloaded
```