返回 Skills
prisma/skills· MIT 内容可用

prisma-cli

Prisma ORM CLI commands reference covering init, generate, migrate, db, dev, studio, validate, format, debug, and mcp. Use for ORM/database CLI workflows, not Prisma Compute app deployment. For Prisma Compute, `@prisma/cli app deploy`, `compute:deploy`, `create-prisma --deploy`, apps, deployments, logs, or domains, use the `prisma-compute` skill instead. Triggers on "prisma init", "prisma generate", "prisma migrate", "prisma db", "prisma studio", "prisma mcp".

安装

与 skills.sh 相同的 Command / Prompt 安装方式


name: prisma-cli description: Prisma ORM CLI commands reference covering init, generate, migrate, db, dev, studio, validate, format, debug, and mcp. Use for ORM/database CLI workflows, not Prisma Compute app deployment. For Prisma Compute, @prisma/cli app deploy, compute:deploy, create-prisma --deploy, apps, deployments, logs, or domains, use the prisma-compute skill instead. Triggers on "prisma init", "prisma generate", "prisma migrate", "prisma db", "prisma studio", "prisma mcp". license: MIT metadata: author: prisma version: "7.6.0"

Prisma CLI Reference

Reference for Prisma ORM CLI commands. This skill provides guidance on command usage, options, and best practices for current Prisma ORM releases.

Boundary: Compute

Do not use this skill for Prisma Compute app deployment. Use prisma-compute for @prisma/cli app deploy, compute:deploy, create-prisma --deploy, Compute apps, deployments, logs, domains, and framework deploy readiness.

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)

Rule Categories by Priority

PriorityCategoryImpactPrefix
1SetupHIGHinit
2GenerationHIGHgenerate
3DevelopmentHIGHdev
4DatabaseHIGHdb-
5MigrationsCRITICALmigrate-
6UtilityMEDIUMstudio, validate, format, debug, mcp

Command Categories

CategoryCommandsPurpose
SetupinitBootstrap new Prisma project
GenerationgenerateGenerate Prisma Client
Validationvalidate, formatSchema validation and formatting
DevelopmentdevLocal Prisma Postgres for development
Databasedb pull, db push, db seed, db executeDirect database operations
Migrationsmigrate dev, migrate deploy, migrate reset, migrate status, migrate diff, migrate resolveSchema migrations
Utilitystudio, mcp, version, debugDevelopment and AI tooling

Quick Reference

Project Setup

# 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 an example model
prisma init --with-model

Client Generation

# Generate Prisma Client
prisma generate

# Watch mode for development
prisma generate --watch

# 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):

bunx --bun prisma init
bunx --bun prisma generate

Local Development Database

# 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

# 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)

# 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)

# 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

# Open Prisma Studio (database GUI)
prisma studio

# Start Prisma's MCP server for AI tools
prisma mcp

# Show version info
prisma version
prisma -v

# Debug information
prisma debug

# Validate schema
prisma validate

# Format schema
prisma format

Current Prisma CLI Setup

New Configuration File

Use prisma.config.ts for CLI configuration:

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'),
  },
})

Current Command Behavior

  • Run prisma generate explicitly after migrate dev, db push, or other schema syncs when you need fresh client output
  • Run prisma db seed explicitly after migrate dev or migrate reset when you need seed data
  • Use prisma db execute --file ... for raw SQL scripts

Environment Variables

Load environment variables explicitly in prisma.config.ts, commonly with dotenv:

// prisma.config.ts
import 'dotenv/config'

Rule Files

See individual rule files for detailed command documentation:

references/init.md           - Project initialization
references/generate.md       - Client generation
references/dev.md            - Local development database
references/db-pull.md        - Database introspection
references/db-push.md        - Schema push
references/db-seed.md        - Database seeding
references/db-execute.md     - Raw SQL execution
references/migrate-dev.md    - Development migrations
references/migrate-deploy.md - Production migrations
references/migrate-reset.md  - Database reset
references/migrate-status.md - Migration status
references/migrate-resolve.md - Migration resolution
references/migrate-diff.md   - Schema diffing
references/studio.md         - Database GUI
references/mcp.md            - Prisma MCP server
references/validate.md       - Schema validation
references/format.md         - Schema formatting
references/debug.md          - Debug info

How to Use

Use the command categories above for navigation, then open the specific command reference file you need.

附带文件

references/db-execute.md
# 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 |
| `--config` | Custom path to your Prisma config file |

## Current Option Surface

`prisma db execute` uses the datasource configured in `prisma.config.ts`. Use `--config` if you need a separate config file for another environment.

## 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 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.
references/db-pull.md
# 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
references/db-push.md
# 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 |

### Follow-up Command

- Run `prisma generate` explicitly when you need refreshed client output

## 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

```bash
prisma db push
prisma generate
```

## 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.
references/db-seed.md
# 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: 'alice@prisma.io' },
    update: {},
    create: {
      email: 'alice@prisma.io',
      name: 'Alice',
      posts: {
        create: {
          title: 'Hello World',
          published: true,
        },
      },
    },
  })

  const bob = await prisma.user.upsert({
    where: { email: 'bob@prisma.io' },
    update: {},
    create: {
      email: 'bob@prisma.io',
      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.

## Current Workflow

Run seeding explicitly after migrations when you need seed data:

```bash
prisma migrate dev --name init
prisma generate
prisma db seed  # Must run explicitly
```

## Idempotent Seeding

Use `upsert` to make seeds re-runnable:

```typescript
// Good: Can run multiple times
await prisma.user.upsert({
  where: { email: 'alice@prisma.io' },
  update: {},  // Don't change existing
  create: { email: 'alice@prisma.io', name: 'Alice' },
})

// Bad: Fails on second run
await prisma.user.create({
  data: { email: 'alice@prisma.io', 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
references/debug.md
# 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
references/dev.md
# 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.
references/format.md
# 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
references/generate.md
# 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

```prisma
generator client {
  provider = "prisma-client"
  output   = "../generated"
}
```

### Current Generator Behavior

- `prisma-client` is the standard generator
- `output` is required when using `prisma-client`
- `prisma-client` supports both ESM and CommonJS via `moduleFormat`
- `compilerBuild` supports `fast` and `small` query compiler artifacts
- Use TypeScript `satisfies` for typed query fragments with `prisma-client`
- Import Prisma Client from your generated output path, for example:

```typescript
import { PrismaClient } from '../generated/prisma/client'
```

### Compiler Build Tuning

Use `compilerBuild` when you need to trade artifact size against the default build:

```prisma
generator client {
  provider      = "prisma-client"
  output        = "../generated"
  compilerBuild = "small"
}
```

- `fast` is the default build for most targets
- `small` is useful for size-constrained targets
- Prisma defaults `vercel-edge` targets to `small`

## Common Patterns

### After schema changes

```bash
prisma migrate dev --name my_migration
prisma generate
```

Run `prisma generate` whenever you need refreshed client code after schema-changing commands.

### 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/
├── browser.ts
├── client.ts
├── commonInputTypes.ts
├── models/
├── enums.ts
├── models.ts
└── ...
```

Import the client:

```typescript
import { PrismaClient, Prisma } from '../generated/prisma/client'
```

Import browser-safe types:

```typescript
import { Prisma } from '../generated/prisma/browser'
import { Role } from '../generated/prisma/enums'
import type { UserModel } from '../generated/prisma/models/User'
```
references/init.md
# 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` - Ensures `.env` is ignored and appends the generated client path

## 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.

### Add an example model

```bash
prisma init --with-model
```

Adds a starter model to the generated schema.

### With preview features

```bash
prisma init --preview-feature relationJoins --preview-feature fullTextSearch
```

## Generated Schema

```prisma
generator client {
  provider = "prisma-client"
  output   = "../generated/prisma"
}

datasource db {
  provider = "postgresql"
}
```

## Generated Config (Node.js default)

```typescript
// prisma.config.ts
import "dotenv/config";
import { defineConfig } from 'prisma/config'

export default defineConfig({
  schema: 'prisma/schema.prisma',
  migrations: {
    path: 'prisma/migrations',
  },
  datasource: {
    url: process.env['DATABASE_URL'],
  },
})
```

## Generated Config (Bun)

```typescript
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 `.env` (and let `prisma.config.ts` read it)
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
6. Run `prisma db seed` explicitly if you want seed data
references/mcp.md
# prisma mcp

Starts Prisma's MCP server for AI development tools.

## Command

```bash
prisma mcp
```

## What It Does

- Starts a Model Context Protocol (MCP) server for your Prisma project
- Exposes Prisma schema and database context to compatible AI tools
- Helps AI assistants understand models, generate queries, and suggest migrations

## Usage

```bash
prisma mcp
```

## Typical Use Cases

- Connect Prisma to ChatGPT, Claude, or other MCP-aware tools
- Give an AI assistant access to your Prisma schema structure
- Help an agent propose queries, schema updates, and migration steps with project context

## Notes

- Run this from the project that contains your Prisma schema and `prisma.config.ts`
- The command is separate from Prisma Studio and does not open a browser UI
- The MCP server wraps Prisma CLI commands. For exact behavior of commands like `migrate dev` or `migrate reset`, follow the underlying CLI command docs rather than relying only on the MCP tool descriptions.

## References

- [Prisma CLI `mcp` command](https://docs.prisma.io/docs/cli/mcp)
- [Prisma MCP Server](https://www.prisma.io/docs/ai/tools/chatgpt)
references/migrate-deploy.md
# 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
references/migrate-dev.md
# 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 |

### Follow-up Commands

- Run `prisma generate` explicitly when you need refreshed client output
- Run `prisma db seed` explicitly when you need seed data

Note: Prisma CLI help for `7.6.0` still says `migrate dev` "trigger[s] generators", but local verification in a temp Prisma 7.6.0 project did not emit generated client files. Treat `prisma generate` as an explicit follow-up step when you need generated artifacts on disk.

## 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

```bash
prisma migrate dev --name my_migration
prisma generate
prisma db seed
```

## 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.
references/migrate-diff.md
# 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.
references/migrate-reset.md
# 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. Stops there - run seed and generate explicitly if needed

**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

## Follow-up Steps

Run `prisma generate` and `prisma db seed` explicitly when you need refreshed client output or seed data after a reset.

## Configuration

Configure the seed script in `prisma.config.ts`, then run it explicitly after reset:

```typescript
export default defineConfig({
  migrations: {
    seed: 'tsx prisma/seed.ts',
  },
})
```

Typical workflow:

```bash
prisma migrate reset --force
prisma generate
prisma db seed
```
references/migrate-resolve.md
# 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)
references/migrate-status.md
# 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.
references/studio.md
# 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

## Recent Studio Capabilities

Recent Prisma Studio releases added richer editor workflows:

- multi-cell selection and editing
- full-table search and more intuitive filtering
- command palette shortcuts
- dark mode
- copy selections as Markdown
- back-relation navigation
- SQL workflows including raw SQL queries

Some recent builds also expose AI-assisted SQL authoring. Treat these as interactive Studio features rather than a replacement for checked-in migrations or application queries.

## 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
- Prisma Studio in Prisma 7 currently targets PostgreSQL, MySQL, and SQLite first
- For reproducible application logic, prefer Prisma Client and checked-in SQL scripts

## 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
references/validate.md
# 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.)