ilk dosyalar

This commit is contained in:
Gökhan ÖZARSLAN 2026-08-16 15:09:05 +03:00
commit 6b5a6d0a71
241 changed files with 43411 additions and 0 deletions

View File

@ -0,0 +1,265 @@
---
name: prisma-cli
description: Prisma ORM CLI commands reference covering init, generate, migrate, db, dev, complete, studio, validate, format, debug, and mcp. Use for ORM/database CLI workflows, not the Prisma Platform CLI. Triggers on "prisma init", "prisma generate", "prisma migrate", "prisma db", "prisma complete", "prisma studio", "prisma mcp".
license: MIT
metadata:
author: prisma
version: "7.9.1"
---
# 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: Platform and Compute
Do not confuse the stable ORM command (`prisma`) with the public-beta Platform package (`@prisma/cli`, binary `prisma-cli`). Use `prisma-compute` for Compute apps and workspace auth, and `prisma-postgres` for Platform projects and databases.
## 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`)
- Generating shell completions (`prisma complete`)
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Setup | HIGH | `init` |
| 2 | Generation | HIGH | `generate` |
| 3 | Development | HIGH | `dev` |
| 4 | Database | HIGH | `db-` |
| 5 | Migrations | CRITICAL | `migrate-` |
| 6 | Utility | MEDIUM | `complete`, `studio`, `validate`, `format`, `debug`, `mcp` |
## Command Categories
| Category | Commands | Purpose |
|----------|----------|---------|
| Setup | `init` | Initialize a 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 | `complete`, `studio`, `mcp`, `version`, `debug` | Shell, development, and AI tooling |
## 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 an example model
prisma init --with-model
```
### Client Generation
```bash
# 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):
```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
# 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
# Generate shell completion code
prisma complete zsh
```
## AI Safety Checkpoint
Prisma blocks destructive commands when it detects an AI agent until the agent has obtained explicit user consent. This covers `migrate reset`, `db push --force-reset`, and `db push --accept-data-loss`.
- Explain the exact data-loss impact and ask for consent immediately before running the command.
- Do not infer consent from earlier or unrelated messages.
- If automation needs the consent variable, set `PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION` to the user's exact consent message. Do not invent the text.
- The Prisma MCP server deliberately has no `migrate-reset` tool.
Read `references/agent-safety.md` before any destructive Prisma command.
## Current Prisma CLI Setup
### New Configuration File
Use `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'),
},
})
```
### 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`:
```typescript
// 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/complete.md - Shell completion generation
references/agent-safety.md - AI consent checkpoint for destructive commands
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.

View File

@ -0,0 +1,27 @@
# AI safety checkpoint for destructive commands
Prisma detects common AI-agent environments and blocks these commands until the user gives explicit consent:
- `prisma migrate reset`
- `prisma db push --force-reset`
- `prisma db push --accept-data-loss`
## Required workflow
1. Inspect the target database/config and explain exactly what can be deleted or reset.
2. Ask the user for explicit consent immediately before the action.
3. Run the command only after that consent.
For an agent-run subprocess, Prisma accepts the exact consent text through:
```bash
PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION='<exact user consent message>' prisma migrate reset --force
```
The value must match the user's message exactly and must not contain added quotes or newlines. Never fabricate consent, reuse an old unrelated approval, or bypass the checkpoint by hiding agent-detection environment variables.
The MCP server has no `migrate-reset` tool. Use the shell command only after consent.
## Reference
- [Prisma ORM 7.9.0 release](https://github.com/prisma/prisma/releases/tag/7.9.0)

View File

@ -0,0 +1,22 @@
# prisma complete
Prints a shell completion script.
```bash
prisma complete zsh
prisma complete bash
prisma complete fish
prisma complete powershell
```
For a direct global CLI installation, load the output using the shell's normal startup mechanism. For example, in zsh:
```bash
source <(prisma complete zsh)
```
Prisma also integrates with supported package-manager completion flows. `npx` and `bunx` do not themselves provide completion; invoke the installed binary or the package manager's supported execution form such as `npm exec` or `bun x`.
## Reference
- [Prisma ORM 7.9.0 release](https://github.com/prisma/prisma/releases/tag/7.9.0)

View File

@ -0,0 +1,78 @@
# 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.

View File

@ -0,0 +1,185 @@
# 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

View File

@ -0,0 +1,150 @@
# 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 |
When Prisma detects an AI agent, `--force-reset` and `--accept-data-loss` require explicit user consent. Follow `agent-safety.md`; never infer or fabricate the consent text.
### 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.

View File

@ -0,0 +1,188 @@
# 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

View File

@ -0,0 +1,46 @@
# 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

View File

@ -0,0 +1,157 @@
# 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.

View File

@ -0,0 +1,48 @@
# 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

View File

@ -0,0 +1,173 @@
# 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'
```

View File

@ -0,0 +1,139 @@
# 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 | - |
| `--no-skills` | Skip the best-effort installation of Prisma agent skills | - |
`prisma init` attempts to install `prisma/skills` for detected agents. This is best-effort and does not make project initialization fail. Use `--no-skills` in minimal or controlled environments.
## 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

View File

@ -0,0 +1,39 @@
# 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 exposes `migrate-status`, `migrate-dev`, and Prisma Studio tooling. It does not expose the destructive `migrate-reset` tool; do not claim it is available or try to bypass that safety boundary.
- For destructive shell commands, follow `agent-safety.md` and obtain explicit user consent.
## References
- [Prisma CLI `mcp` command](https://docs.prisma.io/docs/cli/mcp)
- [Prisma MCP Server](https://www.prisma.io/docs/ai/tools/chatgpt)

View File

@ -0,0 +1,127 @@
# 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

View File

@ -0,0 +1,145 @@
# 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
Run `prisma generate` as an explicit follow-up when you need refreshed generated artifacts. Do not rely on historical CLI help that described generators as part of `migrate dev`.
## 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.

View File

@ -0,0 +1,89 @@
# 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.

View File

@ -0,0 +1,80 @@
# 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.**
When Prisma detects an AI agent, this command is blocked until the user gives explicit consent. Follow `agent-safety.md`; `--force` skips the ordinary prompt but does not constitute user consent for an agent.
## 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
```

View File

@ -0,0 +1,57 @@
# 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)

View File

@ -0,0 +1,65 @@
# 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.

View File

@ -0,0 +1,137 @@
# 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

View File

@ -0,0 +1,53 @@
# 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.)

View File

@ -0,0 +1,216 @@
---
name: prisma-client-api
description: Prisma Client API reference covering model queries, filters, operators, and client methods. Use when writing database queries, using CRUD operations, filtering data, or configuring Prisma Client. Triggers on "prisma query", "findMany", "create", "update", "delete", "$transaction".
license: MIT
metadata:
author: prisma
version: "7.9.1"
---
# Prisma Client API Reference
Complete API reference for Prisma Client. This skill provides guidance on model queries, filtering, relations, and client methods for current Prisma projects.
## When to Apply
Reference this skill when:
- Writing database queries with Prisma Client
- Performing CRUD operations (create, read, update, delete)
- Filtering and sorting data
- Working with relations
- Using transactions
- Configuring client options
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Client Construction | HIGH | `constructor` |
| 2 | Model Queries | CRITICAL | `model-queries` |
| 3 | Query Shape | HIGH | `query-options` |
| 4 | Filtering | HIGH | `filters` |
| 5 | Relations | HIGH | `relations` |
| 6 | Transactions | CRITICAL | `transactions` |
| 7 | Raw SQL | CRITICAL | `raw-queries` |
| 8 | Client Methods | MEDIUM | `client-methods` |
## Quick Reference
- `constructor` - `PrismaClient` setup, adapter wiring, logging, and SQL commenter plugins
- `model-queries` - CRUD operations and bulk operations
- `query-options` - `select`, `include`, `omit`, sort, pagination
- `filters` - scalar and logical filter operators
- `relations` - relation reads and nested writes
- `transactions` - array and interactive transaction patterns
- `raw-queries` - `$queryRaw` and `$executeRaw` safety
- `client-methods` - lifecycle methods, extensions, and `satisfies` patterns for `prisma-client`
## Client Instantiation
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
## Model Query Methods
| Method | Description |
|--------|-------------|
| `findUnique()` | Find one record by unique field |
| `findUniqueOrThrow()` | Find one or throw error |
| `findFirst()` | Find first matching record |
| `findFirstOrThrow()` | Find first or throw error |
| `findMany()` | Find multiple records |
| `create()` | Create a new record |
| `createMany()` | Create multiple records |
| `createManyAndReturn()` | Create multiple and return them |
| `update()` | Update one record |
| `updateMany()` | Update multiple records |
| `updateManyAndReturn()` | Update multiple and return them |
| `upsert()` | Update or create record |
| `delete()` | Delete one record |
| `deleteMany()` | Delete multiple records |
| `count()` | Count matching records |
| `aggregate()` | Aggregate values (sum, avg, etc.) |
| `groupBy()` | Group and aggregate |
## Query Options
| Option | Description |
|--------|-------------|
| `where` | Filter conditions |
| `select` | Fields to include |
| `include` | Relations to load |
| `omit` | Fields to exclude |
| `orderBy` | Sort order |
| `take` | Limit results |
| `skip` | Skip results (pagination) |
| `cursor` | Cursor-based pagination |
| `distinct` | Unique values only |
## Client Methods
| Method | Description |
|--------|-------------|
| `$connect()` | Explicitly connect to database |
| `$disconnect()` | Disconnect from database |
| `$transaction()` | Execute transaction |
| `$queryRaw()` | Execute raw SQL query |
| `$executeRaw()` | Execute raw SQL command |
| `$on()` | Subscribe to events |
| `$extends()` | Add extensions |
## Quick Examples
### Find records
```typescript
// Find by unique field
const user = await prisma.user.findUnique({
where: { email: 'alice@prisma.io' }
})
// Find with filter
const users = await prisma.user.findMany({
where: { role: 'ADMIN' },
orderBy: { createdAt: 'desc' },
take: 10
})
```
### Create records
```typescript
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
name: 'Alice',
posts: {
create: { title: 'Hello World' }
}
},
include: { posts: true }
})
```
### Update records
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: { name: 'Alice Smith' }
})
```
### Delete records
```typescript
await prisma.user.delete({
where: { id: 1 }
})
```
### Transactions
```typescript
const [user, post] = await prisma.$transaction([
prisma.user.create({ data: { email: 'alice@prisma.io' } }),
prisma.post.create({ data: { title: 'Hello', authorId: 1 } })
])
```
## Rule Files
Detailed API documentation:
```
references/constructor.md - PrismaClient constructor options
references/model-queries.md - CRUD operations
references/query-options.md - select, include, omit, where, orderBy
references/filters.md - Filter conditions and operators
references/relations.md - Relation queries and nested operations
references/transactions.md - Transaction API
references/raw-queries.md - $queryRaw, $executeRaw
references/client-methods.md - $connect, $disconnect, $on, $extends
```
## Filter Operators
| Operator | Description |
|----------|-------------|
| `equals` | Exact match |
| `not` | Not equal |
| `in` | In array |
| `notIn` | Not in array |
| `lt`, `lte` | Less than |
| `gt`, `gte` | Greater than |
| `contains` | String contains |
| `startsWith` | String starts with |
| `endsWith` | String ends with |
| `mode` | Case sensitivity |
## Relation Filters
| Operator | Description |
|----------|-------------|
| `some` | At least one related record matches |
| `every` | All related records match |
| `none` | No related records match |
| `is` | Related record matches (1-to-1) |
| `isNot` | Related record doesn't match |
## Resources
- [Prisma Client API Reference](https://www.prisma.io/docs/orm/reference/prisma-client-reference)
- [CRUD Operations](https://www.prisma.io/docs/orm/prisma-client/queries/crud)
- [Filtering and Sorting](https://www.prisma.io/docs/orm/prisma-client/queries/filtering-and-sorting)
## How to Use
Pick the category from the table above, then open the matching reference file for implementation details and examples.

View File

@ -0,0 +1,223 @@
# Client Methods
Prisma Client instance methods.
## $connect()
Explicitly connect to the database:
```typescript
const prisma = new PrismaClient({ adapter })
// Explicit connection
await prisma.$connect()
```
### When to use
Usually not needed - Prisma connects automatically on first query. Use for:
- Fail fast on startup
- Health checks
- Pre-warming connections
```typescript
async function main() {
try {
await prisma.$connect()
console.log('Database connected')
} catch (e) {
console.error('Failed to connect:', e)
process.exit(1)
}
}
```
## $disconnect()
Close database connection:
```typescript
await prisma.$disconnect()
```
### Graceful shutdown
```typescript
process.on('beforeExit', async () => {
await prisma.$disconnect()
})
// Or with SIGTERM
process.on('SIGTERM', async () => {
await prisma.$disconnect()
process.exit(0)
})
```
### In tests
```typescript
afterAll(async () => {
await prisma.$disconnect()
})
```
## $on()
Subscribe to events:
### Query events
```typescript
const prisma = new PrismaClient({
adapter,
log: [{ level: 'query', emit: 'event' }]
})
prisma.$on('query', (e) => {
console.log('Query:', e.query)
console.log('Params:', e.params)
console.log('Duration:', e.duration, 'ms')
})
```
### Log events
```typescript
const prisma = new PrismaClient({
adapter,
log: [
{ level: 'info', emit: 'event' },
{ level: 'warn', emit: 'event' },
{ level: 'error', emit: 'event' }
]
})
prisma.$on('info', (e) => console.log(e.message))
prisma.$on('warn', (e) => console.warn(e.message))
prisma.$on('error', (e) => console.error(e.message))
```
## $extends()
Add extensions for custom behavior:
### Add custom methods
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
client: {
$log: (message: string) => console.log(message)
}
})
prisma.$log('Hello!')
```
### Add model methods
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
model: {
user: {
async findByEmail(email: string) {
return prisma.user.findUnique({ where: { email } })
}
}
}
})
const user = await prisma.user.findByEmail('alice@prisma.io')
```
### Query extensions
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
query: {
user: {
async findMany({ args, query }) {
// Add default filter
args.where = { ...args.where, deletedAt: null }
return query(args)
}
}
}
})
```
### Result extensions
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
result: {
user: {
fullName: {
needs: { firstName: true, lastName: true },
compute(user) {
return `${user.firstName} ${user.lastName}`
}
}
}
}
})
const user = await prisma.user.findFirst()
console.log(user.fullName) // Computed field
```
### Chain extensions
```typescript
const prisma = new PrismaClient({ adapter })
.$extends(loggingExtension)
.$extends(softDeleteExtension)
.$extends(computedFieldsExtension)
```
## $transaction()
See `transactions.md` for details.
## $queryRaw() / $executeRaw()
See `raw-queries.md` for details.
## Type utilities
### Prisma namespace
```typescript
import { Prisma } from '../generated/client'
// Input types
type UserCreateInput = Prisma.UserCreateInput
type UserWhereInput = Prisma.UserWhereInput
// Output types
type User = Prisma.UserGetPayload<{}>
type UserWithPosts = Prisma.UserGetPayload<{
include: { posts: true }
}>
```
### Type-safe query fragments with satisfies
Type-safe query fragments:
```typescript
import { Prisma } from '../generated/client'
const userSelect = {
id: true,
email: true,
name: true
} satisfies Prisma.UserSelect
const user = await prisma.user.findUnique({
where: { id: 1 },
select: userSelect
})
```
With the `prisma-client` generator, use TypeScript `satisfies` for typed query fragments. You may still see older examples that use `Prisma.validator()` with `prisma-client-js`.

View File

@ -0,0 +1,221 @@
# PrismaClient Constructor
Configure Prisma Client when instantiating.
## Basic Instantiation
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
## Constructor Options
### adapter (Required for the SQL provider workflow)
Driver adapter instance:
```typescript
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
### accelerateUrl (For Accelerate users)
```typescript
import { withAccelerate } from '@prisma/extension-accelerate'
const prisma = new PrismaClient({
accelerateUrl: process.env.DATABASE_URL, // prisma:// URL
}).$extends(withAccelerate())
```
### log
Configure logging:
```typescript
const prisma = new PrismaClient({
adapter,
log: ['query', 'info', 'warn', 'error'],
})
```
#### Log levels
| Level | Description |
|-------|-------------|
| `query` | All SQL queries |
| `info` | Informational messages |
| `warn` | Warnings |
| `error` | Errors |
#### Log to events
```typescript
const prisma = new PrismaClient({
adapter,
log: [
{ level: 'query', emit: 'event' },
{ level: 'error', emit: 'stdout' },
],
})
prisma.$on('query', (e) => {
console.log('Query:', e.query)
console.log('Duration:', e.duration, 'ms')
})
```
### errorFormat
Control error formatting:
```typescript
const prisma = new PrismaClient({
adapter,
errorFormat: 'pretty', // 'pretty' | 'colorless' | 'minimal'
})
```
### comments
Attach SQL commenter plugins for observability, tracing, or query insights:
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
import { prismaQueryInsights } from '@prisma/sqlcommenter-query-insights'
import { queryTags, withQueryTags } from '@prisma/sqlcommenter-query-tags'
import { traceContext } from '@prisma/sqlcommenter-trace-context'
const prisma = new PrismaClient({
adapter: new PrismaPg(process.env.DATABASE_URL!),
comments: [prismaQueryInsights(), traceContext(), queryTags()],
})
await withQueryTags({ route: '/api/users', requestId: 'req-123' }, () =>
prisma.user.findMany(),
)
```
Use `comments` only for SQL providers. This is the clean way to add trace or query-shape metadata without changing your query calls.
### transactionOptions
Default transaction settings:
```typescript
const prisma = new PrismaClient({
adapter,
transactionOptions: {
maxWait: 5000, // Max wait to acquire transaction (ms)
timeout: 10000, // Max transaction duration (ms)
isolationLevel: 'Serializable',
},
})
```
### queryPlanCacheMaxSize
Use `queryPlanCacheMaxSize` to limit the in-memory query-plan cache:
```typescript
const prisma = new PrismaClient({
adapter,
queryPlanCacheMaxSize: 2_000,
})
```
The value must be a non-negative integer. Set it to `0` to disable query-plan caching; omit it to use Prisma's default. Treat this as a process-local memory/performance control, not a database prepared-statement setting.
## Singleton Pattern
Prevent multiple client instances in development:
```typescript
// lib/prisma.ts
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}
function createPrismaClient() {
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL!
})
return new PrismaClient({ adapter })
}
export const prisma = globalForPrisma.prisma ?? createPrismaClient()
if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma
}
```
## Next.js Pattern
```typescript
// lib/prisma.ts
import { PrismaClient } from '@/generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const createAdapter = () => new PrismaPg({
connectionString: process.env.DATABASE_URL!
})
const prismaClientSingleton = () => {
return new PrismaClient({ adapter: createAdapter() })
}
declare const globalThis: {
prismaGlobal: ReturnType<typeof prismaClientSingleton>
} & typeof global
const prisma = globalThis.prismaGlobal ?? prismaClientSingleton()
export default prisma
if (process.env.NODE_ENV !== 'production') {
globalThis.prismaGlobal = prisma
}
```
## Query Events
Listen to query events:
```typescript
const prisma = new PrismaClient({
adapter,
log: [{ level: 'query', emit: 'event' }],
})
prisma.$on('query', (e) => {
console.log('Query:', e.query)
console.log('Params:', e.params)
console.log('Duration:', e.duration)
})
```
## Log Events
```typescript
prisma.$on('info', (e) => console.log(e.message))
prisma.$on('warn', (e) => console.warn(e.message))
prisma.$on('error', (e) => console.error(e.message))
```

View File

@ -0,0 +1,256 @@
# Filter Conditions and Operators
Filter operators for the `where` clause.
## Equality
```typescript
// Exact match (implicit)
where: { email: 'alice@prisma.io' }
// Explicit equals
where: { email: { equals: 'alice@prisma.io' } }
// Not equal
where: { email: { not: 'alice@prisma.io' } }
```
## Comparison
```typescript
// Greater than
where: { age: { gt: 18 } }
// Greater than or equal
where: { age: { gte: 18 } }
// Less than
where: { age: { lt: 65 } }
// Less than or equal
where: { age: { lte: 65 } }
// Combined
where: { age: { gte: 18, lte: 65 } }
```
## Lists
```typescript
// In array
where: { role: { in: ['ADMIN', 'MODERATOR'] } }
// Not in array
where: { role: { notIn: ['GUEST', 'BANNED'] } }
```
## String Filters
```typescript
// Contains
where: { email: { contains: 'prisma' } }
// Starts with
where: { email: { startsWith: 'alice' } }
// Ends with
where: { email: { endsWith: '@prisma.io' } }
// Case-insensitive (default for some databases)
where: {
email: {
contains: 'PRISMA',
mode: 'insensitive'
}
}
```
## Null Checks
```typescript
// Is null
where: { deletedAt: null }
// Is not null
where: { deletedAt: { not: null } }
// Using isSet (for optional fields)
where: { middleName: { isSet: true } }
```
## Logical Operators
### AND (implicit)
```typescript
// Multiple conditions = AND
where: {
email: { contains: '@prisma.io' },
role: 'ADMIN'
}
```
### AND (explicit)
```typescript
where: {
AND: [
{ email: { contains: '@prisma.io' } },
{ role: 'ADMIN' }
]
}
```
### OR
```typescript
where: {
OR: [
{ email: { contains: '@gmail.com' } },
{ email: { contains: '@prisma.io' } }
]
}
```
### NOT
```typescript
where: {
NOT: {
role: 'GUEST'
}
}
// Multiple NOT conditions
where: {
NOT: [
{ role: 'GUEST' },
{ verified: false }
]
}
```
### Combined
```typescript
where: {
AND: [
{ verified: true },
{
OR: [
{ role: 'ADMIN' },
{ role: 'MODERATOR' }
]
}
],
NOT: { deletedAt: { not: null } }
}
```
## Relation Filters
### some
At least one related record matches:
```typescript
// Users with at least one published post
where: {
posts: {
some: { published: true }
}
}
```
### every
All related records match:
```typescript
// Users where all posts are published
where: {
posts: {
every: { published: true }
}
}
```
### none
No related records match:
```typescript
// Users with no published posts
where: {
posts: {
none: { published: true }
}
}
```
### is / isNot (1-to-1)
```typescript
// Users with profile in specific country
where: {
profile: {
is: { country: 'USA' }
}
}
// Users without profile
where: {
profile: {
isNot: null
}
}
```
## Array Field Filters
For fields like `String[]`:
```typescript
// Has element
where: { tags: { has: 'typescript' } }
// Has some elements
where: { tags: { hasSome: ['typescript', 'javascript'] } }
// Has every element
where: { tags: { hasEvery: ['typescript', 'prisma'] } }
// Is empty
where: { tags: { isEmpty: true } }
```
## JSON Filters
```typescript
// Path-based filter
where: {
metadata: {
path: ['settings', 'theme'],
equals: 'dark'
}
}
// String contains in JSON
where: {
metadata: {
path: ['bio'],
string_contains: 'developer'
}
}
```
## Full-Text Search
```typescript
// Requires @@fulltext index
where: {
content: {
search: 'prisma database'
}
}
```

View File

@ -0,0 +1,281 @@
# Model Queries
CRUD operations for your Prisma models.
## Read Operations
### findUnique
Find a single record by unique field:
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 }
})
const user = await prisma.user.findUnique({
where: { email: 'alice@prisma.io' }
})
```
#### With composite unique key
```typescript
// Model with @@unique([firstName, lastName])
const user = await prisma.user.findUnique({
where: {
firstName_lastName: {
firstName: 'Alice',
lastName: 'Smith'
}
}
})
```
### findUniqueOrThrow
Same as findUnique but throws if not found:
```typescript
const user = await prisma.user.findUniqueOrThrow({
where: { id: 1 }
})
// Throws PrismaClientKnownRequestError if not found
```
### findFirst
Find first matching record:
```typescript
const user = await prisma.user.findFirst({
where: { role: 'ADMIN' },
orderBy: { createdAt: 'desc' }
})
```
### findFirstOrThrow
```typescript
const user = await prisma.user.findFirstOrThrow({
where: { role: 'ADMIN' }
})
```
### findMany
Find multiple records:
```typescript
const users = await prisma.user.findMany({
where: { role: 'USER' },
orderBy: { name: 'asc' },
take: 10,
skip: 0
})
```
## Create Operations
### create
Create a single record:
```typescript
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
name: 'Alice'
}
})
```
#### With relations
```typescript
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
posts: {
create: [
{ title: 'First Post' },
{ title: 'Second Post' }
]
}
},
include: { posts: true }
})
```
### createMany
Create multiple records:
```typescript
const result = await prisma.user.createMany({
data: [
{ email: 'alice@prisma.io', name: 'Alice' },
{ email: 'bob@prisma.io', name: 'Bob' }
],
skipDuplicates: true // Skip records with duplicate unique fields
})
// Returns { count: 2 }
```
### createManyAndReturn
Create multiple and return them:
```typescript
const users = await prisma.user.createManyAndReturn({
data: [
{ email: 'alice@prisma.io', name: 'Alice' },
{ email: 'bob@prisma.io', name: 'Bob' }
]
})
// Returns array of created users
```
## Update Operations
### update
Update a single record:
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: { name: 'Alice Smith' }
})
```
#### Atomic operations
```typescript
const post = await prisma.post.update({
where: { id: 1 },
data: {
views: { increment: 1 },
likes: { decrement: 1 },
score: { multiply: 2 },
rating: { divide: 2 },
version: { set: 5 }
}
})
```
### updateMany
Update multiple records:
```typescript
const result = await prisma.user.updateMany({
where: { role: 'USER' },
data: { verified: true }
})
// Returns { count: 42 }
```
### updateManyAndReturn
```typescript
const users = await prisma.user.updateManyAndReturn({
where: { role: 'USER' },
data: { verified: true }
})
// Returns array of updated users
```
### upsert
Update or create:
```typescript
const user = await prisma.user.upsert({
where: { email: 'alice@prisma.io' },
update: { name: 'Alice Smith' },
create: { email: 'alice@prisma.io', name: 'Alice' }
})
```
## Delete Operations
### delete
Delete a single record:
```typescript
const user = await prisma.user.delete({
where: { id: 1 }
})
// Returns deleted record
```
### deleteMany
Delete multiple records:
```typescript
const result = await prisma.user.deleteMany({
where: { role: 'GUEST' }
})
// Returns { count: 5 }
// Delete all
const result = await prisma.user.deleteMany({})
```
## Aggregation Operations
### count
```typescript
const count = await prisma.user.count({
where: { role: 'ADMIN' }
})
```
### aggregate
```typescript
const result = await prisma.post.aggregate({
_avg: { views: true },
_sum: { views: true },
_min: { views: true },
_max: { views: true },
_count: { _all: true }
})
```
### groupBy
```typescript
const groups = await prisma.user.groupBy({
by: ['country'],
_count: { _all: true },
_avg: { age: true },
having: {
age: { _avg: { gt: 30 } }
}
})
```
## Return Types
| Method | Returns |
|--------|---------|
| `findUnique` | Record \| null |
| `findUniqueOrThrow` | Record (throws if not found) |
| `findFirst` | Record \| null |
| `findFirstOrThrow` | Record (throws if not found) |
| `findMany` | Record[] |
| `create` | Record |
| `createMany` | { count: number } |
| `createManyAndReturn` | Record[] |
| `update` | Record |
| `updateMany` | { count: number } |
| `delete` | Record |
| `deleteMany` | { count: number } |
| `count` | number |
| `aggregate` | Aggregate result |
| `groupBy` | Group result[] |

View File

@ -0,0 +1,276 @@
# Query Options
Options for controlling query behavior.
## select
Choose specific fields to return:
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
select: {
id: true,
name: true,
email: true,
// password: false (excluded by not including)
}
})
// Returns: { id: 1, name: 'Alice', email: 'alice@prisma.io' }
```
### Select relations
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
select: {
name: true,
posts: {
select: {
title: true,
published: true
}
}
}
})
```
### Select with include inside
```typescript
const user = await prisma.user.findMany({
select: {
name: true,
posts: {
include: {
comments: true
}
}
}
})
```
### Select relation count
```typescript
const users = await prisma.user.findMany({
select: {
name: true,
_count: {
select: { posts: true }
}
}
})
// Returns: { name: 'Alice', _count: { posts: 5 } }
```
## include
Include related records:
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: true,
profile: true
}
})
```
### Filtered include
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: {
where: { published: true },
orderBy: { createdAt: 'desc' },
take: 5
}
}
})
```
### Nested include
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: {
include: {
comments: {
include: {
author: true
}
}
}
}
}
})
```
### Include relation count
```typescript
const users = await prisma.user.findMany({
include: {
_count: {
select: { posts: true, followers: true }
}
}
})
```
## omit
Exclude specific fields:
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
omit: {
password: true
}
})
// Returns all fields except password
```
### Omit in relations
```typescript
const users = await prisma.user.findMany({
omit: { password: true },
include: {
posts: {
omit: { content: true }
}
}
})
```
**Note:** Cannot use `select` and `omit` together.
## where
Filter records:
```typescript
const users = await prisma.user.findMany({
where: {
email: { contains: '@prisma.io' },
role: 'ADMIN'
}
})
```
See `filters.md` for detailed filter operators.
## orderBy
Sort results:
```typescript
// Single field
const users = await prisma.user.findMany({
orderBy: { name: 'asc' }
})
// Multiple fields
const users = await prisma.user.findMany({
orderBy: [
{ role: 'desc' },
{ name: 'asc' }
]
})
```
### Order by relation
```typescript
const users = await prisma.user.findMany({
orderBy: {
posts: { _count: 'desc' }
}
})
```
### Null handling
```typescript
const users = await prisma.user.findMany({
orderBy: {
name: { sort: 'asc', nulls: 'last' }
}
})
```
## take & skip
Pagination:
```typescript
// First page
const users = await prisma.user.findMany({
take: 10,
skip: 0
})
// Second page
const users = await prisma.user.findMany({
take: 10,
skip: 10
})
```
### Negative take (reverse)
```typescript
const lastUsers = await prisma.user.findMany({
take: -10,
orderBy: { id: 'asc' }
})
// Returns last 10 users
```
## cursor
Cursor-based pagination:
```typescript
// First page
const firstPage = await prisma.user.findMany({
take: 10,
orderBy: { id: 'asc' }
})
// Next page using cursor
const nextPage = await prisma.user.findMany({
take: 10,
skip: 1, // Skip the cursor record
cursor: { id: firstPage[firstPage.length - 1].id },
orderBy: { id: 'asc' }
})
```
## distinct
Return unique values:
```typescript
const cities = await prisma.user.findMany({
distinct: ['city'],
select: { city: true }
})
```
### Multiple distinct fields
```typescript
const locations = await prisma.user.findMany({
distinct: ['city', 'country']
})
```

View File

@ -0,0 +1,198 @@
# Raw Queries
Execute raw SQL when Prisma's query API isn't sufficient.
## $queryRaw
Execute SELECT queries and get typed results:
```typescript
const users = await prisma.$queryRaw`
SELECT * FROM "User" WHERE email LIKE ${'%@prisma.io'}
`
```
### With type
```typescript
type User = { id: number; email: string; name: string | null }
const users = await prisma.$queryRaw<User[]>`
SELECT id, email, name FROM "User" WHERE role = ${'ADMIN'}
`
```
### Dynamic table/column names
Use `Prisma.raw()` for identifiers (not safe for user input):
```typescript
import { Prisma } from '../generated/client'
const column = 'email'
const users = await prisma.$queryRaw`
SELECT ${Prisma.raw(column)} FROM "User"
`
```
### With Prisma.sql
Build queries dynamically:
```typescript
import { Prisma } from '../generated/client'
const email = 'alice@prisma.io'
const query = Prisma.sql`SELECT * FROM "User" WHERE email = ${email}`
const users = await prisma.$queryRaw(query)
```
### Join multiple SQL fragments
```typescript
import { Prisma } from '../generated/client'
const conditions = [
Prisma.sql`role = ${'ADMIN'}`,
Prisma.sql`verified = ${true}`
]
const users = await prisma.$queryRaw`
SELECT * FROM "User"
WHERE ${Prisma.join(conditions, ' AND ')}
`
```
## $executeRaw
Execute INSERT, UPDATE, DELETE (returns affected count):
```typescript
const count = await prisma.$executeRaw`
UPDATE "User" SET verified = true WHERE email LIKE ${'%@prisma.io'}
`
console.log(`Updated ${count} users`)
```
### Delete example
```typescript
const deleted = await prisma.$executeRaw`
DELETE FROM "User" WHERE "deletedAt" < ${thirtyDaysAgo}
`
```
### Insert example
```typescript
const inserted = await prisma.$executeRaw`
INSERT INTO "Log" (message, level, timestamp)
VALUES (${message}, ${level}, ${new Date()})
`
```
## $queryRawUnsafe / $executeRawUnsafe
For fully dynamic queries (use with caution!):
```typescript
// ⚠️ SQL injection risk - only use with trusted input
const table = 'User'
const users = await prisma.$queryRawUnsafe(
`SELECT * FROM "${table}" WHERE id = $1`,
userId
)
```
### Parameterized unsafe query
```typescript
const result = await prisma.$executeRawUnsafe(
'UPDATE "User" SET name = $1 WHERE id = $2',
'Alice',
1
)
```
## SQL Injection Prevention
### Safe (parameterized)
```typescript
// ✅ User input is parameterized
const email = userInput
const users = await prisma.$queryRaw`
SELECT * FROM "User" WHERE email = ${email}
`
```
### Unsafe (concatenation)
```typescript
// ❌ SQL injection vulnerability!
const email = userInput
const users = await prisma.$queryRawUnsafe(
`SELECT * FROM "User" WHERE email = '${email}'`
)
```
## Database-Specific Features
### PostgreSQL
```typescript
// Array operations
const users = await prisma.$queryRaw`
SELECT * FROM "User" WHERE 'admin' = ANY(roles)
`
// JSON operations
const users = await prisma.$queryRaw`
SELECT * FROM "User" WHERE metadata->>'theme' = 'dark'
`
```
### MySQL
```typescript
// Full-text search
const posts = await prisma.$queryRaw`
SELECT * FROM Post WHERE MATCH(title, content) AGAINST(${searchTerm})
`
```
## Transactions with Raw Queries
```typescript
await prisma.$transaction(async (tx) => {
await tx.$executeRaw`UPDATE "Account" SET balance = balance - ${amount} WHERE id = ${senderId}`
await tx.$executeRaw`UPDATE "Account" SET balance = balance + ${amount} WHERE id = ${recipientId}`
})
```
## Handling Results
### BigInt handling
PostgreSQL returns BigInt for COUNT:
```typescript
const result = await prisma.$queryRaw<[{ count: bigint }]>`
SELECT COUNT(*) as count FROM "User"
`
const count = Number(result[0].count)
```
### Date handling
```typescript
type Result = { createdAt: Date }
const users = await prisma.$queryRaw<Result[]>`
SELECT "createdAt" FROM "User"
`
// createdAt is already a Date object
```
Invalid JavaScript `Date` values passed to raw queries fail validation instead of being silently serialized as `null`. Validate date input at the application boundary; do not rely on `new Date(badValue)` reaching the database.
When a driver adapter returns an unmapped database-specific error, Prisma surfaces `P2039` with the adapter's preserved original code/message. If those details are missing, fix the adapter mapping rather than parsing rendered error text.

View File

@ -0,0 +1,308 @@
# Relation Queries
Query and modify related records.
## Include Relations
Load related records:
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: true,
profile: true
}
})
```
### Filtered include
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: {
where: { published: true },
orderBy: { createdAt: 'desc' },
take: 5,
select: { id: true, title: true }
}
}
})
```
### Nested include
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: {
include: {
comments: {
include: { author: true }
}
}
}
}
})
```
## Select Relations
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
select: {
name: true,
posts: {
select: { title: true }
}
}
})
```
## Nested Writes
### Create with relations
```typescript
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
posts: {
create: [
{ title: 'Post 1' },
{ title: 'Post 2' }
]
},
profile: {
create: { bio: 'Hello!' }
}
}
})
```
### Create or connect
```typescript
const post = await prisma.post.create({
data: {
title: 'New Post',
author: {
connectOrCreate: {
where: { email: 'alice@prisma.io' },
create: { email: 'alice@prisma.io', name: 'Alice' }
}
}
}
})
```
### Connect existing
```typescript
const post = await prisma.post.create({
data: {
title: 'New Post',
author: {
connect: { id: 1 }
}
}
})
// Shorthand for foreign key
const post = await prisma.post.create({
data: {
title: 'New Post',
authorId: 1
}
})
```
## Update Relations
### Update related records
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: {
posts: {
update: {
where: { id: 1 },
data: { title: 'Updated Title' }
}
}
}
})
```
### Update many related
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: {
posts: {
updateMany: {
where: { published: false },
data: { published: true }
}
}
}
})
```
### Upsert related
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: {
profile: {
upsert: {
create: { bio: 'New bio' },
update: { bio: 'Updated bio' }
}
}
}
})
```
### Disconnect
```typescript
// 1-to-1 optional
const user = await prisma.user.update({
where: { id: 1 },
data: {
profile: { disconnect: true }
}
})
// Many-to-many
const post = await prisma.post.update({
where: { id: 1 },
data: {
tags: {
disconnect: [{ id: 1 }, { id: 2 }]
}
}
})
```
### Delete related
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: {
posts: {
delete: { id: 1 }
}
}
})
// Delete many
const user = await prisma.user.update({
where: { id: 1 },
data: {
posts: {
deleteMany: { published: false }
}
}
})
```
### Set (replace all)
```typescript
// Replace all related records
const post = await prisma.post.update({
where: { id: 1 },
data: {
tags: {
set: [{ id: 1 }, { id: 2 }]
}
}
})
```
## Relation Filters
### some
At least one matches:
```typescript
const users = await prisma.user.findMany({
where: {
posts: { some: { published: true } }
}
})
```
### every
All match:
```typescript
const users = await prisma.user.findMany({
where: {
posts: { every: { published: true } }
}
})
```
### none
None match:
```typescript
const users = await prisma.user.findMany({
where: {
posts: { none: { published: true } }
}
})
```
### is / isNot (1-to-1)
```typescript
const users = await prisma.user.findMany({
where: {
profile: { is: { country: 'USA' } }
}
})
```
## Count Relations
```typescript
const users = await prisma.user.findMany({
select: {
name: true,
_count: {
select: { posts: true, followers: true }
}
}
})
// { name: 'Alice', _count: { posts: 5, followers: 100 } }
```
### Filter counted relations
```typescript
const users = await prisma.user.findMany({
select: {
name: true,
_count: {
select: {
posts: { where: { published: true } }
}
}
}
})
```

View File

@ -0,0 +1,184 @@
# Transactions
Execute multiple operations atomically.
## Sequential Transactions
Array of operations executed in order:
```typescript
const [user, post] = await prisma.$transaction([
prisma.user.create({ data: { email: 'alice@prisma.io' } }),
prisma.post.create({ data: { title: 'Hello', authorId: 1 } })
])
```
### All or nothing
If any operation fails, all are rolled back:
```typescript
try {
await prisma.$transaction([
prisma.user.create({ data: { email: 'alice@prisma.io' } }),
prisma.user.create({ data: { email: 'alice@prisma.io' } }) // Duplicate!
])
} catch (e) {
// Both operations rolled back
}
```
## Interactive Transactions
For complex logic and dependent operations:
```typescript
await prisma.$transaction(async (tx) => {
// Decrement sender balance
const sender = await tx.account.update({
where: { id: senderId },
data: { balance: { decrement: amount } }
})
// Check balance
if (sender.balance < 0) {
throw new Error('Insufficient funds')
}
// Increment recipient balance
await tx.account.update({
where: { id: recipientId },
data: { balance: { increment: amount } }
})
})
```
### Transaction options
```typescript
await prisma.$transaction(
async (tx) => {
// operations
},
{
maxWait: 5000, // Max wait to acquire lock (ms)
timeout: 10000, // Max transaction duration (ms)
isolationLevel: 'Serializable' // Isolation level
}
)
```
### Isolation levels
| Level | Description |
|-------|-------------|
| `ReadUncommitted` | Lowest isolation, can read uncommitted changes |
| `ReadCommitted` | Only read committed changes |
| `RepeatableRead` | Consistent reads within transaction |
| `Serializable` | Highest isolation, serialized execution |
## Nested Writes
Automatic transactions for nested operations:
```typescript
// This is automatically a transaction
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
posts: {
create: [
{ title: 'Post 1' },
{ title: 'Post 2' }
]
},
profile: {
create: { bio: 'Hello!' }
}
}
})
```
## Transaction Client
The `tx` parameter is a Prisma Client scoped to the transaction:
```typescript
await prisma.$transaction(async (tx) => {
// Use tx instead of prisma
await tx.user.create({ ... })
await tx.post.create({ ... })
// Can call methods
const count = await tx.user.count()
})
```
## OrThrow in Transactions
Use with interactive transactions:
```typescript
await prisma.$transaction(async (tx) => {
// If not found, throws and rolls back entire transaction
const user = await tx.user.findUniqueOrThrow({
where: { id: 1 }
})
await tx.post.create({
data: { title: 'New Post', authorId: user.id }
})
})
```
## Best Practices
### Keep transactions short
```typescript
// Good - only DB operations in transaction
const data = prepareData() // Outside transaction
await prisma.$transaction(async (tx) => {
await tx.user.create({ data })
})
```
### Handle errors
```typescript
try {
await prisma.$transaction(async (tx) => {
// operations
})
} catch (e) {
if (e.code === 'P2002') {
// Handle unique constraint violation
}
throw e
}
```
### Use appropriate isolation
```typescript
// Default is fine for most cases
await prisma.$transaction(async (tx) => {
// operations
})
// Use Serializable for strict consistency
await prisma.$transaction(
async (tx) => { /* operations */ },
{ isolationLevel: 'Serializable' }
)
```
## Sequential vs Interactive
| Feature | Sequential | Interactive |
|---------|------------|-------------|
| Syntax | Array | Async function |
| Dependent ops | No | Yes |
| Conditional logic | No | Yes |
| Performance | Better | More flexible |
| Use case | Simple batch | Complex logic |

View File

@ -0,0 +1,192 @@
---
name: prisma-compute
description: Prisma Compute deployment and hosting guide. Use whenever the user mentions Prisma Compute, `prisma.compute.ts`, `defineComputeConfig`, deploying or hosting a Prisma app, `@prisma/cli app deploy`, `compute:deploy`, `create-prisma --deploy`, `PRISMA_SERVICE_TOKEN`, Compute auth/workspaces, apps/deployments/build logs/domains, localhost vs `0.0.0.0`, deploy port binding, or framework deploy readiness for Hono, Elysia, Next.js, TanStack Start, Astro, Nuxt, Svelte, Nest, Turborepo, or custom/prebuilt artifacts.
license: MIT
metadata:
author: prisma
version: "1.5.1"
---
# Prisma Compute
Guide agents through Prisma Compute app creation, deployment, operations, and framework-specific deploy readiness.
## Prisma Compute CLI Surface
Use the Prisma Platform CLI for Compute app workflows:
```bash
bunx @prisma/cli@latest app deploy --help
bunx @prisma/cli@latest app --help
bunx @prisma/cli@latest build logs --help
bunx create-prisma@latest --help
```
Use `@prisma/cli@latest` for Compute app deployment. Use `create-prisma@latest` for new-project scaffolding.
## Send Feedback and Report CLI Issues
The CLI has a built-in feedback channel. Use it whenever a command crashes (`UNEXPECTED_ERROR`), a failure survives troubleshooting, or the user asks to send feedback to the Prisma team:
```bash
bunx @prisma/cli@latest feedback "app deploy crashed: <first error line>"
bunx @prisma/cli@latest feedback "love the deploy flow" --email you@example.com
```
Crash output points here on its own: `--json` crash envelopes carry the exact pre-filled command as a `recover` entry in `nextActions` (run it verbatim), and human crash output ends with a `Tell us what happened:` hint. Feedback is anonymous unless `--email` is passed and attaches only the CLI version, node version, and OS platform/arch. Never include secrets, connection URLs, or user data in the message.
## Source-of-Truth Order
Use evidence in this order when deciding what to edit or run:
1. The project's generated scripts and config, especially `prisma.compute.ts`, `compute:deploy`, framework config, and `package.json`.
2. CLI help output from `create-prisma` and `@prisma/cli`.
3. Local installed package code, generated artifacts, and type definitions.
4. Official docs.
## When to Apply
Use this skill for:
- Creating a new app that can deploy to Prisma Compute
- Deploying an existing TypeScript app to Prisma Compute
- Creating or updating a typed `prisma.compute.ts` deploy config
- Deciding whether a framework is Compute-ready
- Debugging `create-prisma --deploy`, `compute:deploy`, or `app deploy`
- Managing Compute app logs, deployments, environment variables, and domains, and listing platform branches (`branch list`; there are no branch create/remove commands)
- Inspecting GitHub/Console build logs and GitHub push-to-deploy status
- Running non-interactive deploys with browser auth, multiple stored workspaces, or Prisma service tokens
- Switching, selecting, listing, or logging out local Prisma Platform workspaces for `@prisma/cli`
- Sending feedback about an unresolvable Compute CLI failure with `@prisma/cli feedback`
- Programmatic deployments with `@prisma/compute-sdk` or Management API integrations
## Decision Tree
1. Existing project deployment or redeploy:
Read [`references/app-deploy-cli.md`](references/app-deploy-cli.md).
2. Typed Compute config, monorepos, deploy targets, app roots, or build/env defaults:
Read [`references/compute-config.md`](references/compute-config.md).
3. Framework-specific build/runtime work:
Read [`references/frameworks.md`](references/frameworks.md).
4. New project from a scaffold:
Read [`references/create-prisma.md`](references/create-prisma.md).
5. Programmatic deployment, SDKs, APIs, or low-level App/Deployment concepts:
Read [`references/sdk-api.md`](references/sdk-api.md).
6. Build, auth, env, deploy, or runtime failures:
Read [`references/troubleshooting.md`](references/troubleshooting.md).
## Rules by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Command verification | CRITICAL | `verify-` |
| 2 | Auth and workspace selection | CRITICAL | `auth-` |
| 3 | Framework readiness | CRITICAL | `framework-` |
| 4 | Runtime host and port binding | CRITICAL | `runtime-` |
| 5 | Typed Compute config | HIGH | `config-` |
| 6 | Branch, environment, and database wiring | HIGH | `env-` |
| 7 | Deploy operations | HIGH | `deploy-` |
| 8 | SDK and API automation | MEDIUM | `sdk-` |
## Quick Rules
### 1. Command Verification
- `verify-help-first` - Use CLI help output to confirm command syntax while working.
- `verify-prisma-vs-platform-cli` - Do not assume `prisma app deploy` exists in the ORM CLI; check whether the task should use `@prisma/cli`.
- `verify-generated-scripts` - Prefer the generated `compute:deploy` script when a project already has one.
- `verify-public-url` - After a real deploy, request the public deployment URL instead of trusting local or readiness-only checks.
- `verify-config-support` - Treat `prisma.compute.ts` as the typed Compute config; inspect the project's config and generated scripts before editing or deploying.
- `verify-auth-workspace-support` - Use `@prisma/cli auth workspace` commands for local workspace list/use/logout flows.
### 2. Auth and Workspace Selection
- `auth-source-precedence` - A non-empty `PRISMA_SERVICE_TOKEN` is the active auth source for commands and local OAuth workspaces are ignored for execution. If it is set but empty, the CLI should fail instead of falling back to stored OAuth.
- `auth-multi-workspace` - `auth login` can store OAuth sessions for multiple workspaces on the same machine. The active workspace pointer selects which stored OAuth grant normal commands use.
- `auth-list-before-switch` - Use `auth workspace list --json` to inspect local sessions. Agents should prefer workspace ids from JSON over names because names can be ambiguous.
- `auth-switch-explicitly` - Use `auth workspace use <id-or-name>` for non-interactive switching. Use `auth workspace use` with no argument only for an interactive picker or when exactly one local OAuth workspace exists.
- `auth-no-fallthrough` - If the active OAuth workspace is logged out or fails refresh, the CLI should not silently fall through to another cached workspace. Run `auth workspace use <id>` to choose the next workspace.
- `auth-single-workspace-logout` - Use `auth workspace logout <id-or-name>` or `auth logout --workspace <id-or-name>` to remove one local OAuth workspace session. Plain `auth logout` clears all local OAuth workspace sessions.
- `auth-service-token-switching` - While `PRISMA_SERVICE_TOKEN` is set, `auth workspace use` is unavailable because the service token is the active auth source; unset the env var to switch local OAuth workspaces. Workspace logout still only cleans local OAuth state.
- `auth-storage-awareness` - Local OAuth credentials live in the platform auth file, with workspace metadata in a sidecar context file. Project pins live in `.prisma/local.json`, and CLI app/project state lives in `.prisma/cli/state.json` near `prisma.compute.ts` when present.
### 3. Framework Readiness
- `framework-cli-first` - Evaluate deploy readiness against `@prisma/cli app deploy`, not against what `create-prisma` can scaffold.
- `framework-supported-cli-deploy` - Compute deploy supports `nextjs`, `nuxt`, `astro`, `hono`, `nestjs`, `tanstack-start`, `custom`, and `bun`.
- `framework-create-prisma-defaults-only` - `create-prisma` can provide generated defaults and `compute:deploy`, but it is not the general deploy surface for existing apps.
- `framework-build-output` - Compute needs a server entrypoint or framework artifact, not only static output.
### 4. Runtime Host and Port Binding
- `runtime-bind-all-interfaces` - Deployed servers must bind on all interfaces (`0.0.0.0` or the framework equivalent), not hard-coded `localhost` or `127.0.0.1`.
- `runtime-match-http-port` - The app must listen on the deployed HTTP port: read `process.env.PORT` when possible, or pass the matching `--http-port`.
- `runtime-readiness-port-only` - Compute readiness watches listening ports; a loopback-only listener can look ready while public ingress cannot reach it.
### 5. Typed Compute Config
- `config-optional-simple-app` - `prisma.compute.ts` is not required to deploy a normal single app; use flags when there is no durable config.
- `config-init-formalizer` - Generate a fresh config with `bunx @prisma/cli@latest init`: it detects the framework, pins name/framework/httpPort (plus entry for Bun/Hono), and offers the Project link. `--format json` writes a dependency-free `prisma.compute.json` instead. `init` refuses when any config already exists, never scaffolds code, and never deploys.
- `config-use-prisma-compute-ts` - Put reusable deploy defaults in `prisma.compute.ts` with `defineComputeConfig`, not in `prisma.config.ts`.
- `config-app-vs-apps` - Use `app` for a single deploy target and `apps` for monorepos or multi-app repos; define exactly one.
- `config-monorepo-roots` - For monorepos, use `prisma.compute.ts` to declare app targets, roots, framework defaults, entrypoints, ports, and env inputs.
- `config-targets` - In multi-app configs, `@prisma/cli app deploy web` selects the `apps.web` target. Without `[app]`, commands can infer the target from the current directory; otherwise deploy can run all targets while build/run require one.
- `config-region-new-app-only` - A config `region` is only a default for newly created apps; deploys to existing apps keep the app's current region.
- `config-custom-artifact` - Use `framework: "custom"` with `build.outputDirectory` and `build.entrypoint` for prebuilt or custom-built artifacts.
- `config-no-project-branch-secrets` - Do not commit Workspace, Project, Branch, production intent, service tokens, or secret values in `prisma.compute.ts`; keep those in flags, `.prisma/local.json`, env storage, or CI secrets. App-level defaults such as `region`, `root`, `framework`, `entry`, `httpPort`, and non-secret env file paths belong in config.
- `config-flags-win` - Explicit deploy flags such as `--framework`, `--entry`, `--http-port`, `--region`, and `--env` override matching config values.
### 6. Branch, Environment, and Database
- `env-do-not-leak-secrets` - Never print full `DATABASE_URL`, service tokens, or secret values.
- `env-deploy-loads-dotenv` - Generated deploy scripts may load env via `prisma.compute.ts` or `--env .env`; inspect the actual script/config before redeploy.
- `env-migrations-separate` - Redeploy scripts do not run migrations or seed data. Run the appropriate Prisma database scripts separately.
- `env-cli-token-name` - `@prisma/cli` uses `PRISMA_SERVICE_TOKEN` for service-token auth.
- `env-branch-scope` - Branch deploys, branch env vars, and branch databases must use the same branch name; pass `--branch <git-name>` explicitly when targeting a preview branch.
- `env-production-vs-preview` - Use `--role production` for production env, `--role preview` for preview template env, and `--branch <git-name>` for branch-specific overrides.
- `env-db-explicit` - Keep database and env wiring explicit through database and project env commands; deploy examples should not add database setup, and deploys do not run migrations, seed data, or create one database per app automatically.
### 7. Deploy Operations
- `deploy-prod-intent` - Use `--prod --yes` only when the user intends a production deploy. The first production deploy of an App auto-promotes without `--prod`; the flag gates subsequent production-branch deploys.
- `deploy-no-promote` - Use `app deploy --no-promote` for build-then-verify: it builds a candidate reachable at its own URL without touching the live deployment, promoted later with `app promote <deployment-id>`.
- `deploy-github-default-branch` - When a Compute app is connected to GitHub push-to-deploy, a merge to the default branch is the production deploy path; check deployment records or GitHub check runs instead of telling users to redeploy the merged PR branch or run a default-branch preview deploy.
- `deploy-build-logs` - Use `@prisma/cli build logs <build-id>` for GitHub/Console build output. Use `app logs` for runtime deployment logs; the two ids are different.
- `deploy-noninteractive-auth` - Non-interactive deploys need either the correct active stored OAuth workspace or a supported service token env var; never print the token.
- `deploy-json-for-agents` - Use `--json --no-interactive` for scripts and agent-readable output.
- `deploy-create-project` - Use `--create-project <name>` only when the user wants deploy to create and link a new project; it conflicts with `--project` and `PRISMA_PROJECT_ID`.
- `deploy-ops-targets` - App show/open/logs/list-deploys/promote/rollback/remove and domain commands can also accept `[app]` targets from `prisma.compute.ts`.
- `deploy-report-cli-bugs` - On `UNEXPECTED_ERROR` or an unresolvable failure, report it with the feedback command; see "Send Feedback and Report CLI Issues" above.
### 8. SDK and API
- `sdk-use-cli-first` - Prefer `@prisma/cli app deploy` for app workflows; use `create-prisma` only to scaffold a new app unless the user is building lower-level automation.
- `sdk-result-handling` - `@prisma/compute-sdk` returns `Result` values; check `isOk()`/`isErr()` instead of relying on exceptions.
- `sdk-snapshot-detection` - Use `detectComputeApp` for repository snapshots that are not checked out to disk; enumerate workspaces yourself and call it once per candidate app root.
## Preferred Workflow
1. Inspect the project: package manager, template/framework, `package.json` scripts, Prisma version, Prisma client location, `prisma.compute.ts`, and existing `compute:deploy`.
2. Verify CLI help output for the package actually being used.
3. Verify auth context before project/app mutations: `auth whoami --json`, and when multiple local sessions may exist, `auth workspace list --json`.
4. Choose the path:
- existing app deploy: config-backed target when present, generated `compute:deploy`, or `@prisma/cli app build/run/deploy` flags
- new app scaffold: `create-prisma`, then generated `compute:deploy` or `@prisma/cli app deploy`
- low-level automation: `@prisma/compute-sdk` or Management API
5. Check framework readiness plus host/port/env/runtime requirements, including project and branch scope.
6. Run a local build or `app build` before deploying when feasible.
7. Deploy with JSON output when automating, then request the public URL and summarize app URL, app id, deployment id, project id, workspace id, and follow-up steps.
8. For GitHub/Console builds, inspect the `Prisma Compute Deploy` check run or `build logs <build-id>` before guessing why a build failed.
## Avoid
- Do not bury Compute deployment guidance in the generic `prisma-cli` skill.
- Do not run `create-prisma` inside an existing app just to deploy it; use the generated `compute:deploy` script or `@prisma/cli app deploy`.
- Do not tell users that every `create-prisma` template can auto-deploy.
- Do not deploy with placeholder `DATABASE_URL` values.
- Do not assume `next start` is the Compute runtime path; Next.js deploys need standalone output.

View File

@ -0,0 +1,403 @@
# Prisma Platform CLI App Deploy
Use this reference for existing projects and for generated `compute:deploy` scripts.
## Package and Command
Compute app workflows are exposed through the Prisma Platform CLI package:
```bash
bunx @prisma/cli@latest --help
bunx @prisma/cli@latest app --help
bunx @prisma/cli@latest app deploy --help
bunx @prisma/cli@latest build logs --help
```
The examples in help output may call the binary `prisma-cli`. When using package runners, prefer:
```bash
bunx @prisma/cli@latest app deploy
npx @prisma/cli@latest app deploy
pnpm dlx @prisma/cli@latest app deploy
```
## Agent Skill Installation
`@prisma/cli` can install and refresh Prisma skills for local AI coding agents:
```bash
bunx @prisma/cli@latest agent install
bunx @prisma/cli@latest agent install --skill prisma-compute
bunx @prisma/cli@latest agent update
bunx @prisma/cli@latest agent status --json
```
`agent install` and `agent update` shell out to `skills@latest add prisma/skills` through the detected package runner. Use them when the user wants Prisma's agent context installed or refreshed; they are not a deployment command.
## Typed Compute Config
`prisma.compute.ts` is optional for normal single-app deploys and useful for reusable defaults or multi-app targets. Read [`compute-config.md`](compute-config.md) for config shapes, target selection, precedence, and monorepo rules. This reference only shows how deploy commands consume those settings.
## Auth and Project Binding
Useful commands:
```bash
bunx @prisma/cli@latest auth login
bunx @prisma/cli@latest auth whoami
bunx @prisma/cli@latest project list --json
bunx @prisma/cli@latest project show
bunx @prisma/cli@latest project link <project-id-or-name>
```
`@prisma/cli` can keep multiple local browser-login workspace sessions. Running `auth login` again for a different workspace should add/update that workspace session and make it active; it should not delete the existing workspace session. The active workspace pointer decides which stored OAuth workspace normal commands use.
For agents, prefer this flow before project/app mutations:
```bash
bunx @prisma/cli@latest auth whoami --json
bunx @prisma/cli@latest auth workspace list --json
bunx @prisma/cli@latest auth workspace use <workspace-id>
```
Use workspace ids from `auth workspace list --json` when possible. Names are friendlier for humans but can be ambiguous. Use `auth workspace use` with no argument for a human interactive picker; headless scripts should pass an id because no-argument `use` fails non-interactively when multiple local OAuth workspaces exist.
If the active workspace is logged out or its refresh fails, the CLI intentionally does not auto-select another cached workspace. Choose the next workspace explicitly:
Use `auth workspace list --json`, then `auth workspace use <workspace-id>`.
To clean up one local OAuth workspace without clearing every stored workspace session:
```bash
bunx @prisma/cli@latest auth workspace logout <workspace-id-or-name>
# equivalent:
bunx @prisma/cli@latest auth logout --workspace <workspace-id-or-name>
```
Plain `auth logout` clears all local OAuth workspace sessions. It does not unset `PRISMA_SERVICE_TOKEN`.
For a new linked project:
```bash
bunx @prisma/cli@latest project create my-app --json
```
For non-interactive or CI work, `@prisma/cli` accepts a workspace service token through `PRISMA_SERVICE_TOKEN`. A non-empty service token takes precedence over stored browser-login credentials, so local OAuth workspace switching does not affect command execution while the env var is set. `auth workspace list --json` may still show local OAuth sessions, but they are not switchable until the service-token env var is unset. Verify auth with `auth whoami` and never print the token value.
If `PRISMA_SERVICE_TOKEN` is set but empty, unset it or provide a real token. The CLI should fail instead of silently falling back to local OAuth credentials.
Local auth storage is useful for debugging but should not be printed verbatim:
- `PRISMA_COMPUTE_AUTH_FILE` can override the auth file path.
- On macOS, the default OAuth credentials file is `~/Library/Application Support/prisma/auth.json`.
- Workspace metadata and the active workspace pointer live beside it as `auth.context.json`.
- Project pins live in `.prisma/local.json`.
- Local CLI state such as selected app and known live deployment lives in `.prisma/cli/state.json`, rooted near `prisma.compute.ts` when a config is discovered.
## Project, Branch, Database, and Env Scope
Compute deploys resolve a target project, app, and branch. Be explicit when the user's intent is not the already linked default project/app:
```bash
bunx @prisma/cli@latest project show --json
bunx @prisma/cli@latest app deploy --project proj_123 --app my-api --branch feature/login --json
```
If `prisma.compute.ts` defines a `name` or an `apps` key, that config can provide the app name. `--app` and `PRISMA_APP_ID` rank above the config value. `[app]` selects a target from `apps`:
```bash
bunx @prisma/cli@latest app deploy api --project proj_123 --branch feature/login --json
```
See [`compute-config.md`](compute-config.md) for no-argument target inference, deploy-all, and build/run target rules.
Branch scope must line up across deploys, databases, and env vars:
- `app deploy --branch <git-name>` creates a deployment for that branch.
- `database create <name> --branch <git-name>` creates a Prisma Postgres database for that branch scope.
- `project env add/update/list/remove --branch <git-name>` manages branch-specific env overrides.
- `project env add/update/list/remove --role production` manages production env.
- `project env add/update/list/remove --role preview` manages preview-template env.
Do not assume a local Git branch was used by the CLI unless the generated script or command output says so. If a user asks for `feature/login`, pass `--branch feature/login` consistently to app, database, and env commands.
Promotion is a separate production action: `app promote <deployment-id>` rebuilds a deployment with production env vars. Do not treat a preview branch deploy as production promotion.
## Deployment Story: GitHub vs CLI
When a Compute app is connected to GitHub push-to-deploy, the default branch is the production deploy path. If a PR has been merged into `main` or another configured default branch, the natural answer is that the changes should appear in production after the production deployment completes; use CLI deploys for explicit manual deploys, local-source deploys, or repositories that are not using GitHub push-to-deploy.
`app show`, `app list-deploys`, and `app logs` expose `--app`, `--project`, and for logs `--deployment`, not `--branch`. For branch debugging, capture the deployment id from deploy JSON and inspect that deployment or its logs.
`app deploy --create-project <name>` creates and links a new Project before deploying. Use it only when the user wants a new Project. It conflicts with `--project` and `PRISMA_PROJECT_ID`, and `--yes` alone does not choose Project scope.
`app deploy --region <region>` only applies when deploy creates a new app. Existing apps keep their current region. Use `prisma.compute.ts` `region` for a durable default, and use the flag only for one-off new-app placement.
## Database and Env
Create a Prisma Postgres database for the linked project:
```bash
bunx @prisma/cli@latest database create main --branch main --json
```
Manage project env vars:
```bash
bunx @prisma/cli@latest project env list
bunx @prisma/cli@latest project env add --file .env --role production
bunx @prisma/cli@latest project env add --file .env.preview --role preview
bunx @prisma/cli@latest project env add DATABASE_URL=postgresql://... --branch feature/foo
bunx @prisma/cli@latest project env update --file .env --role production
bunx @prisma/cli@latest project env update DATABASE_URL=postgresql://... --branch feature/foo
bunx @prisma/cli@latest project env list --branch feature/foo
bunx @prisma/cli@latest project env remove STRIPE_KEY --role preview
```
`app deploy --env .env` loads environment variables from a file for the deployment. A config-backed deploy can instead load env through `prisma.compute.ts` `env`. Neither path is a migration command or seed command.
Database setup is not part of `prisma.compute.ts`. Keep database intent explicit with `database create` and project env commands. Do not add database setup to deploy examples. Treat any generated connection URL as a one-time secret.
Database and env guardrails:
- Deploys do not run migrations, seed data, or schema push. Run the app's own Prisma database command after deploy setup when needed.
- In deploy-all, every target on the same branch shares branch-scoped project env unless you assign app-specific env values yourself.
- Existing database env values supplied through `--env DATABASE_URL=...`, `--env DIRECT_URL=...`, an env file, or project env should be treated as the source of truth.
- Known non-PostgreSQL Prisma schema sources should not be wired to Prisma Postgres automatically.
## Project Git, Branch, and Database Operations
These commands are part of the same Platform CLI surface and often matter while preparing Compute deploys:
```bash
bunx @prisma/cli@latest branch list --json
bunx @prisma/cli@latest git connect git@github.com:org/repo.git --project proj_123
bunx @prisma/cli@latest git disconnect --project proj_123
bunx @prisma/cli@latest database list --branch feature/foo --json
bunx @prisma/cli@latest database show db_123 --json
bunx @prisma/cli@latest database remove db_123 --confirm db_123
bunx @prisma/cli@latest database connection list db_123 --json
bunx @prisma/cli@latest database connection create db_123 --name readonly
bunx @prisma/cli@latest database connection remove conn_123 --confirm conn_123
bunx @prisma/cli@latest database connection rotate conn_123 --confirm conn_123
bunx @prisma/cli@latest database usage db_123 --json
bunx @prisma/cli@latest database backup list db_123 --json
bunx @prisma/cli@latest database restore db_123 --backup bkp_123 --confirm db_123
bunx @prisma/cli@latest project rename new-name --project proj_123
bunx @prisma/cli@latest project transfer proj_123 --to-workspace wksp_456 --confirm proj_123
bunx @prisma/cli@latest project remove proj_123 --confirm proj_123
```
Destructive and ownership-changing commands (`remove`, `restore`, `transfer`, `connection rotate`) require exact `--confirm <id>`; `--yes` is not enough.
Git integration connects a Project to a GitHub repository. Console-side GitHub import can create a Compute app and trigger push-to-deploy for the connected repository, including default-branch production deploys. The CLI `git connect` command is setup, not a local deploy command; use `app deploy` for explicit CLI deploys.
For GitHub-driven deploys, inspect the Console/build-runner state, deployment records, build logs, or the `Prisma Compute Deploy` GitHub check run instead of assuming local CLI output exists. The build runner can perform branch-aware database/env wiring: a preview branch with a Prisma schema and no `DATABASE_URL` can get a branch-scoped preview database, while production can wire a missing `DATABASE_URL` template from an existing ready database. GitHub check runs are the guided feedback path; do not promise Vercel-style PR comments.
Database and database-connection commands never print stored secret values in list/show output. `database create` and `database connection create` return a one-time connection URL; treat it as a secret, store it immediately in env if needed, and do not echo it back in summaries. Removal requires exact `--confirm <id>`; `--yes` is not enough.
## Build and Run Locally
Before deploy, verify that the app can produce a Compute artifact:
```bash
bunx @prisma/cli@latest app build --build-type auto
bunx @prisma/cli@latest app run --build-type auto --port 3000
```
For Bun/server entrypoints:
```bash
bunx @prisma/cli@latest app build --build-type bun --entry src/index.ts
bunx @prisma/cli@latest app run --build-type bun --entry src/index.ts --port 8080
```
For NestJS, use `app build` to validate the Compute artifact and run the framework's own dev command locally:
```bash
bunx @prisma/cli@latest app build --build-type nestjs
bun run dev
```
With a compute config, pass the target name instead of repeating framework/entry/port flags:
```bash
bunx @prisma/cli@latest app build api
bunx @prisma/cli@latest app run api --port 8080
```
`app run --port` sets `PORT` for local development. It does not rewrite an app's explicit host binding, so a local run is not enough to prove the deployed server is reachable from ingress.
`app run --build-type nestjs` is not supported. If a config-backed NestJS target is selected, run the Nest dev server directly instead.
## Deploy
Deploy with prompts:
```bash
bunx @prisma/cli@latest app deploy
```
Agent/script-friendly deploy (do not assume production; add `--prod --yes` only when the user intends a production deploy, and note the first production deploy of an App auto-promotes without `--prod`):
```bash
bunx @prisma/cli@latest app deploy \
--json \
--no-interactive \
--env .env
```
Build-then-verify path for CI: `--no-promote` builds a candidate deployment without changing the live one; it is reachable at its own candidate URL and promoted later with `app promote <deployment-id>`:
```bash
bunx @prisma/cli@latest app deploy --no-promote --json --no-interactive
```
For preview branches, omit `--prod` unless the user explicitly intends a production deploy:
```bash
bunx @prisma/cli@latest app deploy \
--branch feature/foo \
--json \
--no-interactive \
--env .env.preview
```
After a real deploy, verify the public deployment URL. Do not stop at "deploy succeeded" or a local `app run` check:
```bash
curl -i https://<deployment-url>
```
If the deploy command returns JSON, parse the URL from the result and request that exact public URL. Do not accidentally test `localhost` or `127.0.0.1` instead of public ingress.
Create/link a project during deploy:
```bash
bunx @prisma/cli@latest app deploy \
--create-project my-app \
--prod \
--yes \
--env .env
```
Deploy with framework and port:
```bash
bunx @prisma/cli@latest app deploy \
--framework hono \
--http-port 8080 \
--prod \
--yes \
--env .env
```
Deploy a newly created app in a specific region:
```bash
bunx @prisma/cli@latest app deploy \
--app my-api \
--region us-west-1 \
--prod \
--yes \
--env .env
```
`--region` is a new-app placement hint. It does not move an existing app.
Deploy a preview branch with framework and port:
```bash
bunx @prisma/cli@latest app deploy \
--framework hono \
--branch feature/foo \
--http-port 8080 \
--json \
--no-interactive \
--env .env.preview
```
Bun-style app with explicit entrypoint:
```bash
bunx @prisma/cli@latest app deploy \
--framework bun \
--entry src/index.ts \
--http-port 8080 \
--prod \
--yes \
--env .env
```
`--entry <path>` without `--framework` is treated as a Bun app deploy.
Config-backed Bun-style app:
```bash
bunx @prisma/cli@latest app deploy api --prod --yes --env .env
```
Use config for stable app defaults, and flags for one-off project, branch, region, env, and production choices. Keep database setup in explicit database and project-env commands.
## Operations
Inspect and open:
```bash
bunx @prisma/cli@latest app show --json
bunx @prisma/cli@latest app open
```
Deployments:
```bash
bunx @prisma/cli@latest app list-deploys --json
bunx @prisma/cli@latest app show-deploy <deployment-id> --json
bunx @prisma/cli@latest app promote <deployment-id> --yes
bunx @prisma/cli@latest app rollback --to <deployment-id> --yes
bunx @prisma/cli@latest app remove --app my-api --yes
```
Logs:
```bash
bunx @prisma/cli@latest app logs
bunx @prisma/cli@latest app logs --deployment <deployment-id>
bunx @prisma/cli@latest app logs --json
```
Build logs for GitHub/Console builds:
```bash
bunx @prisma/cli@latest build logs <build-id>
bunx @prisma/cli@latest build logs <build-id> --follow
bunx @prisma/cli@latest build logs <build-id> --json
```
`build logs` streams build output keyed by a Build id from a GitHub/Console build or check run. It is separate from runtime `app logs`, which are keyed by the current app deployment or a deployment id.
Domains:
```bash
bunx @prisma/cli@latest app domain add shop.example.com
bunx @prisma/cli@latest app domain show shop.example.com
bunx @prisma/cli@latest app domain wait shop.example.com --timeout 15m
bunx @prisma/cli@latest app domain retry shop.example.com
bunx @prisma/cli@latest app domain remove shop.example.com
```
Custom domain commands target production branch runtime. Do not use a preview branch for production domain setup.
## Output Handling
When `--json` is available, parse the JSON and summarize:
- project id/name
- branch name
- app id/name
- deployment id/status
- build id when present
- deployment URL
- database id/name if one was created
Do not print secret env var values.

View File

@ -0,0 +1,222 @@
# Prisma Compute Config
Use this reference when creating or updating `prisma.compute.ts`, especially for monorepos, multi-app deploys, reusable framework defaults, env inputs, ports, entrypoints, or build settings.
`prisma.compute.ts` is not required for every deploy. A simple app can deploy with `@prisma/cli app deploy --framework ... --entry ... --http-port ... --env ...`. The config file exists to make those app-level defaults typed and repeatable.
For monorepos or multi-app repositories, use `prisma.compute.ts`: it is the practical way to tell Compute which app target lives at which `root` and which framework/entry/env defaults belong to each target.
## Generating a Config with `init`
Prefer `bunx @prisma/cli@latest init` over hand-writing a fresh single-app config. It detects the framework from the same registry deploy uses, pins `name`, `framework`, and `httpPort` (plus `entry` for Bun and Hono), previews every value with its source, offers the `@prisma/compute-sdk` devDependency for editor types, and offers the Project link. Useful flags: `--framework`, `--entry`, `--http-port`, `--name`, `--no-link`, `--json`.
`--format json` writes a dependency-free static `prisma.compute.json` instead of the TypeScript config; a later explicit `init --format ts` converts it in place when the config needs to become programmatic. `init` fails with `INIT_CONFIG_EXISTS` when any compute config already exists, never scaffolds application code, and never deploys. Multi-app monorepo configs are still written by hand.
## File Names and Discovery
The canonical file is `prisma.compute.ts`. The loader also accepts:
```text
prisma.compute.mts
prisma.compute.js
prisma.compute.mjs
prisma.compute.cjs
prisma.compute.json
```
`prisma.compute.json` is the static, dependency-free variant of the same config; it is discovered and loaded like the others.
Keep exactly one compute config file in a directory. If multiple names exist together, the CLI reports `COMPUTE_CONFIG_INVALID`.
The CLI searches from the invocation directory up to the repository or workspace boundary. Boundaries include `.git`, `pnpm-workspace.yaml`, `bun.lock`, `bun.lockb`, or `package.json#workspaces`. Config-relative paths such as `root` and `env.file` resolve from the config file directory. `--env` flag paths still resolve from the invocation directory.
When a config is discovered, its directory becomes the Compute project directory for local state: `.prisma/local.json` and `.prisma/cli/state.json` live beside that config, not necessarily inside the app root.
## Basic Shape
Import `defineComputeConfig` from `@prisma/compute-sdk/config`. The CLI aliases this helper when loading the config, so the command can evaluate the config without a local SDK install solely for runtime loading.
```typescript
import { defineComputeConfig } from "@prisma/compute-sdk/config";
export default defineComputeConfig({
app: {
name: "api",
framework: "hono",
httpPort: 8080,
env: ".env",
},
});
```
JavaScript configs can default-export a plain object, but prefer `prisma.compute.ts` for type checking.
Define exactly one of:
- `app` for a single deploy target
- `apps` for a monorepo or multi-app repository
Do not define both. Besides `app`/`apps`, the only other allowed top-level key is `region`: a project-level default region applied when deploy creates new apps, overridable per app and by `--region`.
## App Fields
Each app target accepts:
| Field | Meaning |
|-------|---------|
| `name` | Deployed app name. Defaults to the `apps` key, then CLI inference. |
| `region` | Compute region id used only when deploy creates a new app. Existing apps keep their current region. |
| `root` | App directory relative to the config file. Defaults to the config directory. |
| `framework` | Deploy framework: `nextjs`, `nuxt`, `astro`, `hono`, `nestjs`, `tanstack-start`, `custom`, or `bun`. |
| `entry` | Entrypoint path for Bun/Hono-style deploys, relative to the app root. |
| `httpPort` | Deployed HTTP port. Use this for fixed-port apps. |
| `env` | Dotenv file path string, or `{ file, vars }`. Paths resolve from the config directory. |
| `build` | `{ command, outputDirectory, entrypoint }`. Present means the config owns build settings for that target. |
`env` examples:
```typescript
export default defineComputeConfig({
app: {
framework: "nextjs",
env: {
file: [".env", ".env.production"],
vars: {
NODE_ENV: "production",
},
},
},
});
```
Do not put secrets directly in committed `vars`. Keep secret values in platform env, CI secrets, or dotenv files that are intentionally managed outside version control.
`build` examples:
```typescript
export default defineComputeConfig({
app: {
framework: "nextjs",
build: {
command: "pnpm build",
outputDirectory: ".next/standalone",
},
},
});
```
Use `command: null` to skip the build step only when the app root already contains the deployable artifact.
For a custom or prebuilt artifact, make the deploy target explicit:
```typescript
export default defineComputeConfig({
app: {
framework: "custom",
build: {
command: "npm run build",
outputDirectory: "build",
entrypoint: "handler.js",
},
},
});
```
`build.entrypoint` is relative to `build.outputDirectory` when an output directory is set. For Bun/Hono configs without an output directory, an entrypoint-backed build can supply the source entrypoint. Do not set both `entry` and `build.entrypoint` unless they describe the same file.
A config `build` block is accepted for every supported framework: the config-backed build types are `nextjs`, `nuxt`, `astro`, `nestjs`, `tanstack-start`, `custom`, and `bun` (`hono` builds through the `bun` strategy). Only `custom` requires one (`build.outputDirectory` and `build.entrypoint`); for the others it overrides inferred build settings.
## Monorepos and Multi-App Repos
For monorepos, put `prisma.compute.ts` at the repo or workspace root and use `apps`. This keeps project binding and local `.prisma/` state at the repo root while each app builds from its own `root`.
```typescript
import { defineComputeConfig } from "@prisma/compute-sdk/config";
export default defineComputeConfig({
apps: {
web: {
root: "apps/web",
framework: "nextjs",
env: "apps/web/.env",
},
api: {
root: "apps/api",
framework: "hono",
entry: "src/index.ts",
httpPort: 8080,
env: {
file: "apps/api/.env",
vars: {
LOG_LEVEL: "info",
},
},
},
frontend: {
root: "apps/frontend",
framework: "custom",
build: {
command: "pnpm --filter frontend build",
outputDirectory: "dist/server",
entrypoint: "index.mjs",
},
},
},
});
```
Target selection:
```bash
bunx @prisma/cli@latest app deploy web
bunx @prisma/cli@latest app deploy api
bunx @prisma/cli@latest app build api
bunx @prisma/cli@latest app run api --port 8080
```
If no `[app]` argument is passed, commands can infer the target from the invocation directory when it is inside a configured `root`. The deepest matching root wins. If no target is inferred from a multi-app config, a bare deploy can deploy all targets in declaration order:
```bash
bunx @prisma/cli@latest app deploy --branch feature/foo --json --no-interactive
```
Deploy-all rejects per-app overrides such as `--app`, `--framework`, `--entry`, `--http-port`, `--region`, `--env`, and `PRISMA_APP_ID`. Project, branch, production, and confirmation flags still apply to the whole run. Keep database setup in explicit database and project-env commands.
`app build` and `app run` still need one target in multi-app configs because a local build/run command cannot operate N apps at once.
Additional target rules:
- A single-entry `apps` map can deploy its only target without an argument.
- With a single `app` config, `[app]` is accepted only when it equals the configured `name`.
- `[app]` without any compute config file is a usage error.
## Precedence
Explicit flags win over config values:
- `--framework` overrides `framework`
- `--entry` overrides `entry`
- `--http-port` overrides `httpPort`
- `--region` overrides `region`
- any `--env` flag replaces all config env inputs
- `--app` and `PRISMA_APP_ID` rank above config app names
`region` is not an app selector. Config `region` and `--region` are only used when deploy creates a new app. If the selected app already exists, deploy keeps that app's existing region.
`prisma.compute.ts` never selects Workspace, Project, Branch, or production intent. Keep those in CLI flags, environment variables, `.prisma/local.json`, or CI configuration:
```bash
bunx @prisma/cli@latest app deploy api \
--project proj_123 \
--branch feature/foo \
--prod \
--yes
```
## Database Scope
The config does not declare databases. Keep database intent in `database create`, project env commands, or external automation. Read [`app-deploy-cli.md`](app-deploy-cli.md) for deploy-all, migration, and env-var guardrails.
## Relationship to `prisma.config.ts`
Do not put Compute deploy defaults in `prisma.config.ts`. Prisma ORM uses `prisma.config.ts`, while Compute uses `prisma.compute.ts`.

View File

@ -0,0 +1,117 @@
# create-prisma Compute Flow
Use this reference when creating a new app with Prisma and optionally deploying it to Prisma Compute.
Do not use `create-prisma` as the deploy path for an existing app. For existing projects, use the generated `compute:deploy` script when present, or call `bunx @prisma/cli@latest app deploy` directly.
## Reference
Useful scaffold checks:
```bash
bunx create-prisma@latest --help
bunx create-prisma@latest --version
```
Use `create-prisma@latest` for new-project scaffolding.
## Supported Templates
`create-prisma@latest` scaffolds `hono`, `elysia`, `nest`, `next`, `svelte`, `astro`, `nuxt`, `tanstack-start`, and `turborepo`.
Integrated `--deploy` support applies to `hono`, `elysia`, `nest`, `next`, `astro`, `nuxt`, `tanstack-start`, and `turborepo`. For `turborepo`, the generated config target is usually `api`.
The scaffold template name is `nest`, but the Compute deploy framework/config key is `nestjs`.
`svelte` is scaffold-only for Compute because `@prisma/cli app deploy --framework` has no `svelte` key.
## Basic Commands
Interactive creation:
```bash
bunx create-prisma@latest
```
Non-interactive scaffold only:
```bash
bunx create-prisma@latest \
--name my-api \
--template hono \
--provider postgresql \
--no-install \
--no-generate \
--no-migrate-and-seed \
--no-deploy
```
Create and deploy a supported template:
```bash
bunx create-prisma@latest \
--name my-api \
--template hono \
--provider postgresql \
--deploy
```
## PostgreSQL and Database Behavior
With PostgreSQL, no explicit `--database-url`, and no `--no-prisma-postgres`, the Compute flow can create:
- a Prisma Compute project
- a `main` Prisma Postgres database on the `main` branch
- a `.env` file containing `DATABASE_URL`
- an initial Compute deployment with env vars loaded from `.env`
`create-prisma` is the new-project path. If the user needs a later preview branch deploy, use the generated `compute:deploy` script or `@prisma/cli app deploy --branch <git-name>` after the app exists. Keep branch names aligned across `app deploy --branch`, `database create --branch`, and `project env ... --branch`.
For unattended local tests, pass `--no-prisma-postgres` unless you intentionally want provisioning:
```bash
bunx create-prisma@latest \
--name smoke-app \
--template hono \
--provider postgresql \
--no-prisma-postgres \
--database-url "postgresql://USER:PASSWORD@HOST:PORT/DB" \
--no-deploy
```
Do not deploy placeholder database URLs. If `DATABASE_URL` came from a placeholder default, omit it from deploy env and ask the user for a real production database.
## Generated Deploy Script
When the deploy flow is selected, `create-prisma` can add:
```json
{
"scripts": {
"compute:deploy": "bunx @prisma/cli@latest app deploy --prod --yes ..."
}
}
```
Use the actual generated script from `package.json`; do not reconstruct it from memory. The script redeploys app code using generated flags and/or `prisma.compute.ts`. It does not create a new project, create a new database, run migrations, or seed data. If a scaffolded project does not have `compute:deploy`, use `@prisma/cli app deploy` directly.
Inspect the generated `package.json`, `prisma.compute.ts`, and README before editing deploy behavior.
## Generated Files to Preserve
Preserve generated framework runtime files and `prisma.compute.ts` unless you are intentionally changing the deploy target. For framework-specific deploy/runtime details, read [`frameworks.md`](frameworks.md).
All Prisma 7 scaffolds:
- use `prisma.config.ts`
- load `dotenv/config` where the runtime supports it
- generate Prisma Client into a template-local path such as `src/generated/prisma`
- use `@prisma/adapter-pg` with a `DATABASE_URL` connection string for PostgreSQL
## Addon Notes
`create-prisma` supports `--skills`, `--mcp`, and `--extension`. Those are separate from Compute deployment. Do not imply that enabling skills or MCP deploys the app.
## Failure Handling
If `--deploy` is explicit and setup cannot authenticate, cannot run the Platform CLI, or cannot complete the integrated deploy, report that deploy failed and keep the scaffolded project. Do not delete the user's files.

View File

@ -0,0 +1,382 @@
# Prisma Compute Framework Readiness
Use this reference when deciding whether and how an app can deploy to Prisma Compute.
## CLI-First Model
Treat `@prisma/cli app deploy` as the deployment surface. Treat `create-prisma` as a new-project scaffold that can generate useful defaults and, for some templates, a `compute:deploy` script.
Compute deploy supports these framework keys:
```text
nextjs
nuxt
astro
hono
nestjs
tanstack-start
custom
bun
```
Auto-detection:
- Next.js: `next.config.*` or `next` dependency
- Nuxt: `nuxt.config.*` or `nuxt` dependency
- Astro: `astro.config.*` or `astro` dependency
- Hono: `hono` dependency
- NestJS: `nest-cli.json` or `@nestjs/core` dependency
- TanStack Start: `@tanstack/react-start` or `@tanstack/solid-start`
- Custom artifact: explicit `framework: "custom"` plus `build.outputDirectory` and `build.entrypoint` in `prisma.compute.ts`
- Bun: explicit `--entry <path>` or `--framework bun`
If detection is ambiguous, set `framework` in `prisma.compute.ts` or pass a supported `--framework` value. If the app is a source-level plain server, use `framework: "bun"` plus `entry`, or pass `--framework bun --entry <path>`, after verifying the server entrypoint. If the app already produces a runnable Node artifact, use `framework: "custom"` with `build.outputDirectory` and `build.entrypoint`.
## CLI Matrix
| App shape | Deploy command shape | Auto-detected | Required output/entry | Notes |
|-----------|----------------------|---------------|-----------------------|-------|
| Next.js | `--framework nextjs` | Yes | standalone `server.js` output | Requires `output: "standalone"` |
| Nuxt | `--framework nuxt` | Yes | `.output/server/index.mjs` | Framework strategy supplies build defaults; a config `build` block is optional |
| Astro | `--framework astro` | Yes | standalone Node server artifact | Framework strategy supplies build defaults; a config `build` block is optional |
| Hono | `--framework hono` | Yes | Bun entry from `main`, `module`, `--entry`, or `src/index.ts` | Usually fixed port `8080` in generated config/scripts |
| NestJS | `--framework nestjs` | Yes | NestJS server artifact | Omit host or bind to `0.0.0.0`; a config `build` block is optional |
| TanStack Start | `--framework tanstack-start` | Yes | `.output/server/index.mjs` | Requires Nitro node output |
| Custom artifact | config-backed `framework: "custom"` | No | configured `build.outputDirectory` and `build.entrypoint` | Use for prebuilt/custom-built Node artifacts |
| Bun / plain server | `--framework bun --entry <path>` | With explicit entry | server entrypoint | Use for Elysia and custom HTTP servers |
| Elysia | `--framework bun --entry src/index.ts` | No dedicated deploy key | Bun entrypoint | Preserve port/host handling |
| SvelteKit | No deploy framework key | No | Node adapter/prebuilt artifact | Do not deploy `vite preview` |
| Turborepo | Deploy concrete app targets | No | app-specific entry/output | Prefer `prisma.compute.ts` with `apps` |
`app build --build-type` uses the framework build type. Build types include `auto`, `nextjs`, `nuxt`, `astro`, `nestjs`, `tanstack-start`, `custom`, and `bun`.
`app run --build-type` is local-dev oriented and supports `auto`, `bun`, and `nextjs`. It streams the local dev server and is not proof that the deployed app is reachable through public ingress.
`prisma.compute.ts` can set framework, entrypoint, HTTP port, env inputs, app root, region, and build settings. A config `build` block is accepted for every supported framework; all build types are config-backed (`nextjs`, `nuxt`, `astro`, `nestjs`, `tanstack-start`, `custom`, `bun`; `hono` builds through the `bun` strategy). For Nuxt, Astro, and NestJS the framework strategy supplies the default build command and output, so a `build` block is optional and normally unnecessary, but it overrides those defaults when present. Only `custom` requires one.
Config snippets below assume:
```typescript
import { defineComputeConfig } from "@prisma/compute-sdk/config";
```
## Universal Runtime Requirements
Compute needs a server process:
- It must listen on the deployed HTTP port. `@prisma/cli app deploy` defaults to the framework's default HTTP port (3000 for most frameworks, 4321 for Astro) unless `--http-port` is passed.
- It must bind on all interfaces. Do not hard-code `localhost` or `127.0.0.1` for a deployed server; use `0.0.0.0`, `server.host: true`, or the framework equivalent.
- It must have a deployable entrypoint or recognized framework output.
- It must not rely on a preview-only command such as `vite preview`.
- It must receive env vars through `--env`, project env, branch env, or external automation.
Check host and port together. A listener on the right port but bound to loopback can appear ready while public ingress cannot reach it.
## Next.js
Deploy shape:
```bash
bunx @prisma/cli@latest app deploy --framework nextjs --env .env
```
`next.config.ts` must include standalone output:
```typescript
import type { NextConfig } from "next"
const nextConfig: NextConfig = {
output: "standalone",
}
export default nextConfig
```
Do not pass `--entry` with `nextjs`; the CLI derives the runtime entrypoint from framework build output.
Do not set `HOSTNAME=localhost` or `HOSTNAME=127.0.0.1` in deploy env. If the standalone server host is overridden, use `0.0.0.0`.
## Hono
Deploy shape:
```bash
bunx @prisma/cli@latest app deploy \
--framework hono \
--http-port 8080 \
--env .env
```
Config shape:
```typescript
export default defineComputeConfig({
app: {
framework: "hono",
entry: "src/index.ts",
httpPort: 8080,
env: ".env",
},
});
```
Project expectations:
- `package.json` has `main` or `module` pointing at the entrypoint, or deploy passes `--entry src/index.ts`
- server uses `@hono/node-server`
- code reads `process.env.PORT` and defaults to the same port used by `--http-port`
- code does not set `hostname` to `localhost` or `127.0.0.1`; if hostname is set explicitly, use `0.0.0.0`
Example runtime shape:
```typescript
const rawPort = (process.env.PORT ?? "").trim()
const parsedPort = rawPort.length > 0 ? Number(rawPort) : Number.NaN
const port = Number.isInteger(parsedPort) ? parsedPort : 8080
serve({ fetch: app.fetch, port })
```
## NestJS
Deploy shape:
```bash
bunx @prisma/cli@latest app deploy --framework nestjs --env .env
```
Config shape:
```typescript
export default defineComputeConfig({
app: {
framework: "nestjs",
env: ".env",
},
});
```
Project expectations:
- detection uses `nest-cli.json` or the `@nestjs/core` dependency; pass `--framework nestjs` when neither signal is present
- `src/main.ts` or the compiled runtime must start an HTTP server
- read `process.env.PORT` and default to the same port used by `--http-port`
- omit the host argument in `app.listen(port)` or pass `"0.0.0.0"`; do not pass `"localhost"` or `"127.0.0.1"`
- use `app build --build-type nestjs` for a Compute artifact check; `app run --build-type nestjs` is not supported, so use the Nest dev server locally
Example runtime shape:
```typescript
const port = Number(process.env.PORT ?? "3000")
await app.listen(port)
```
## TanStack Start
Deploy shape:
```bash
bunx @prisma/cli@latest app deploy --framework tanstack-start --env .env
```
Expected `vite.config.ts` shape:
```typescript
import { defineConfig } from "vite"
import viteReact from "@vitejs/plugin-react"
import { tanstackStart } from "@tanstack/react-start/plugin/vite"
import { nitro } from "nitro/vite"
export default defineConfig({
plugins: [tanstackStart(), nitro(), viteReact()],
})
```
Preserve these details:
- keep `nitro` in `dependencies`
- keep `import { nitro } from "nitro/vite"`
- keep `nitro()` in the Vite plugin list
- keep the React Vite plugin after `tanstackStart()`
- keep Nitro on its default node server preset; do not switch to edge, static, Cloudflare, or another non-Node preset for Compute
The build command is `vite build`. The build must produce `.output/server/index.mjs`, and the production start shape is:
```json
{
"scripts": {
"build": "vite build",
"start": "node .output/server/index.mjs"
}
}
```
Do not deploy TanStack Start as a Bun entrypoint such as `src/router.tsx`. If `.output/server/index.mjs` is missing, fix the TanStack/Nitro build path.
Make sure Nitro does not bind only to localhost in deployment. If host env/config is customized, use the framework's all-interface host setting rather than `localhost`.
## Nuxt
Deploy shape:
```bash
bunx @prisma/cli@latest app deploy --framework nuxt --env .env
```
Config shape:
```typescript
export default defineComputeConfig({
app: {
framework: "nuxt",
env: ".env",
},
});
```
Nuxt uses Nitro output at `.output/server/index.mjs`. Keep the Nitro preset compatible with a Node server runtime.
## Astro
Deploy shape:
```bash
bunx @prisma/cli@latest app deploy --framework astro --env .env
```
Config shape:
```typescript
export default defineComputeConfig({
app: {
framework: "astro",
httpPort: 4321,
env: ".env",
},
});
```
Astro Compute-style server output usually needs:
```javascript
import { defineConfig } from "astro/config"
import node from "@astrojs/node"
export default defineConfig({
output: "server",
adapter: node({ mode: "standalone" }),
server: { host: true },
})
```
## Bun, Elysia, and Plain Source Servers
Use the Bun deploy key for app shapes without a dedicated `--framework` value:
```bash
bunx @prisma/cli@latest app deploy \
--framework bun \
--entry src/index.ts \
--http-port 8080 \
--env .env
```
`app deploy` also treats `--entry <path>` without `--framework` as a Bun app deploy.
Requirements:
- pass `--entry` unless `package.json` `main` or `module` points at the runtime entrypoint
- ensure the entrypoint starts an HTTP server, not only exports handlers
- read `process.env.PORT` or align `--http-port` with the fixed listener port
- bind on all interfaces
Elysia example:
```typescript
const port = Number(process.env.PORT ?? "8080")
app.listen({ port, hostname: "0.0.0.0" })
```
## Custom Build Artifacts
Use `framework: "custom"` when the app is already built, or when a custom command produces a runnable Node artifact that Compute should stage as-is:
```typescript
export default defineComputeConfig({
app: {
framework: "custom",
build: {
command: "npm run build",
outputDirectory: "build",
entrypoint: "handler.js",
},
httpPort: 3000,
env: ".env",
},
});
```
Requirements:
- set both `build.outputDirectory` and `build.entrypoint`
- make `build.entrypoint` relative to `build.outputDirectory`
- ensure the artifact starts an HTTP server and binds on all interfaces
- use `command: null` only when the output directory already contains the deployable artifact
## SvelteKit and Other Frameworks
`@prisma/cli app deploy --framework` has no `svelte` framework key. Do not claim SvelteKit is directly deployable with that name.
For frameworks without a dedicated deploy key, use one of these paths:
- produce a Node server artifact and deploy with config-backed `framework: "custom"`, or through a supported prebuilt/SDK flow
- if the app has a plain Node/Bun server entrypoint, deploy that entrypoint through `--framework bun --entry <path>`
SvelteKit should use a Node adapter or another production server artifact. Do not use `vite preview` as the deployed runtime.
## Turborepo
Deploy concrete app packages, not the monorepo root by default. Prefer `prisma.compute.ts` at the repo root with one `apps` entry per deploy target.
Checklist:
- choose the app directory, such as `apps/api`
- run the workspace build from the correct root/package
- pass the app package's runtime entrypoint or framework
- pass the correct env file, which may live outside the app package
- keep branch env/database scope aligned with the deployed app
Example config:
```typescript
export default defineComputeConfig({
apps: {
web: { root: "apps/web", framework: "nextjs" },
api: {
root: "apps/api",
framework: "bun",
entry: "src/index.ts",
httpPort: 3000,
env: "packages/db/.env",
},
},
});
```
Deploy one target:
```bash
bunx @prisma/cli@latest app deploy api --branch feature/foo --json
```
Flag-only shape after confirming output paths:
```bash
bun run build
bunx @prisma/cli@latest app deploy \
--framework bun \
--entry apps/api/dist/src/index.js \
--http-port 3000 \
--env packages/db/.env
```
Verify the actual output path before using this command.

View File

@ -0,0 +1,167 @@
# SDK and API Automation
Use this reference when building automation rather than using `create-prisma` or `@prisma/cli app deploy`.
## Prefer the CLI for App Workflows
For normal app deployment:
1. Use generated `compute:deploy` when present.
2. Otherwise use `@prisma/cli app build/run/deploy`.
3. Use SDK/API only for custom automation, platform integrations, or tool builders.
## Compute SDK
Install:
```bash
npm install @prisma/compute-sdk @prisma/management-api-sdk
```
Config helper:
```typescript
import { defineComputeConfig } from "@prisma/compute-sdk/config";
```
Use this import in `prisma.compute.ts` for type checking. The helper is an identity function; the CLI loader aliases the import when it evaluates config files, so a user project does not need the SDK solely to load a Compute config.
Create an authenticated Management API client:
```typescript
import { createManagementApiClient } from "@prisma/management-api-sdk"
const apiClient = createManagementApiClient({
token: process.env.PRISMA_API_TOKEN,
})
```
Token naming differs by surface. `@prisma/cli app ...` uses `PRISMA_SERVICE_TOKEN` for non-interactive service-token auth. The SDK examples here use `PRISMA_API_TOKEN` as an application convention for passing a token into `createManagementApiClient`; the SDK itself only receives the `token` string.
Deploy a prebuilt artifact:
```typescript
import { ComputeClient, PreBuilt } from "@prisma/compute-sdk"
const compute = new ComputeClient(apiClient)
const databaseUrl = process.env.DATABASE_URL
if (!databaseUrl) throw new Error("DATABASE_URL is required")
const result = await compute.deploy({
strategy: new PreBuilt({
appPath: "./dist",
entrypoint: "index.js",
}),
projectId: "proj_abc",
appName: "my-app",
// region: "us-east-1", // optional: explicit placement for a new app
envVars: { DATABASE_URL: databaseUrl },
portMapping: { http: 3000 },
})
if (result.isOk()) {
console.log(result.value.deploymentEndpointDomain)
} else {
console.error(result.error.message)
}
```
SDK methods return `Result<T, E>`. Check `isOk()` or `isErr()` instead of assuming errors throw. Deploy results expose app/deployment vocabulary including `appId`, `appName`, `projectId`, `region`, `deploymentId`, `deploymentEndpointDomain`, `appEndpointDomain`, `promoted`, `previousDeploymentId`, `previousDeploymentAction`, and `resolvedConfig`.
## SDK Build Strategies
Project Compute SDK strategies:
- `AutoBuild`: tries supported framework strategies such as Next.js, Nuxt, Astro, NestJS, TanStack Start, then Bun
- `NextjsBuild`: requires standalone output and returns `server.js`
- `NuxtBuild`: expects `.output/server/index.mjs`
- `AstroBuild`: expects `dist/server/entry.mjs`
- `NestjsBuild`: builds a NestJS HTTP server artifact
- `TanstackStartBuild`: runs `vite build` and expects a Nitro node server at `.output/server/index.mjs`; keep `tanstackStart()` and `nitro()` in Vite config
- `CustomBuild`: runs optional configured build settings and stages a configured artifact entrypoint
- `BunBuild`: runs `bun build` and needs an explicit entrypoint or `package.json` `main`
- `PreBuilt`: uses an existing artifact directory and relative entrypoint
## Regions
Known SDK region ids:
```text
us-east-1
us-west-1
eu-west-3
eu-central-1
ap-northeast-1
ap-southeast-1
```
Use `--region` in `@prisma/cli app deploy` or `region` in SDK deploy input only when creating a new Compute app. Existing apps keep their current region.
`region` is optional on `deploy` and `createApp`. Omit it to use the Project/platform default when creating an app; do not hard-code a region unless placement is an application requirement.
## Repository-snapshot detection
Tooling that already has an in-memory repository tree can detect a deployable app without checking files out:
```typescript
import { detectComputeApp } from '@prisma/compute-sdk/config'
const detected = detectComputeApp({
root: 'apps/api',
manifest: {
main: 'src/index.ts',
scripts: { start: 'bun src/index.ts' },
dependencies: { hono: '^4' },
},
filePaths: ['apps/api/package.json', 'apps/api/src/index.ts'],
})
```
The result contains `framework`, `frameworkName`, `buildType`, `httpPort`, `entrypoint`, and detection `evidence`, or `null` when nothing is deployable. Paths are repository-relative and unsafe absolute/parent-traversal entrypoints are rejected.
The helper detects one app root. A monorepo consumer must enumerate workspaces and call it once per candidate. Detection reads `dependencies` and `devDependencies` (not peer dependencies), recognizes config files and framework packages, and can infer Bun-backed servers from valid `start`/`serve` script entrypoints.
## Management API Concepts
Compute resources map roughly to:
- Project: parent container
- Branch: production or preview scope for env resolution and database/env attachment
- App: stable app endpoint and branch attachment
- Deployment: build artifact plus runtime status and preview URL
Low-level public routes use App/Deployment names:
- list/create apps under a project with `/v1/apps`
- get/update/delete an app
- create/list deployments for an app
- get/start/stop/delete deployments with `/v1/deployments/:deploymentId`
- promote or roll back an app using `deploymentId`
- stream logs with `/v1/deployments/:deploymentId/logs`
- manage custom domains
Internal compatibility aliases may still appear in code. Prefer App/Deployment names in new docs, skills, and automation.
Environment variables are not embedded directly in the low-level deployment create payload. The attached branch's role selects their scope: a preview branch resolves branch-scoped vars, while a production branch (or no branch) resolves project-scoped production vars. Use project/environment-variable APIs or CLI env commands to write env vars first, and keep the branch name consistent across app creation, database creation, and env writes.
When using the CLI alongside SDK automation:
```bash
bunx @prisma/cli@latest project env add --file .env.preview --branch feature/foo
bunx @prisma/cli@latest database create preview-db --branch feature/foo --json
bunx @prisma/cli@latest app deploy --branch feature/foo --json --no-interactive
```
Production promotion is not just "the same branch with another label"; `app promote <deployment-id>` rebuilds with production env vars.
## Secrets and Redaction
Management API deployment inspection exposes env var names with redacted values. Treat any value like `[redacted]` as a marker, not as the deployed value.
Do not log:
- service tokens
- OAuth tokens
- full database URLs
- env var values
- pre-signed upload URLs

View File

@ -0,0 +1,454 @@
# Troubleshooting Prisma Compute
Use this reference when setup, build, deploy, env, or runtime behavior fails.
## First Checks
Run:
```bash
bunx @prisma/cli@latest --help
bunx @prisma/cli@latest app deploy --help
bunx @prisma/cli@latest auth whoami
bunx @prisma/cli@latest auth workspace list --json
```
Then inspect:
```bash
pwd
cat package.json
find .. -maxdepth 3 \( -name 'prisma.compute.ts' -o -name 'prisma.compute.mts' -o -name 'prisma.compute.js' -o -name 'prisma.compute.mjs' -o -name 'prisma.compute.cjs' \) -print
test -f .env && sed -n 's/=.*/=<redacted>/p' .env
```
Do not print unredacted secrets.
## `prisma.compute.ts` Not Picked Up
This only matters when the project is supposed to use a config-backed deploy. A simple app without `prisma.compute.ts` can still deploy with explicit `app deploy` flags.
Symptoms:
- deploy ignores the expected framework, entrypoint, port, env file, or app root
- a monorepo target such as `api` is not recognized
- local state appears in the wrong `.prisma/` directory
Check:
```bash
pwd
find .. -maxdepth 4 \( -name 'prisma.compute.ts' -o -name 'prisma.compute.mts' -o -name 'prisma.compute.js' -o -name 'prisma.compute.mjs' -o -name 'prisma.compute.cjs' \) -print
bunx @prisma/cli@latest app deploy --help
```
Fix:
- keep exactly one compute config file in the directory where it lives
- put repo-wide or monorepo config at the repository/workspace root
- run commands from inside the repo or workspace boundary so discovery can walk up to the config
- use `[app]` targets from the `apps` keys, such as `bunx @prisma/cli@latest app deploy api`
- remember that config-relative paths such as `root` and `env.file` resolve from the config file directory
## Compute Config Invalid
Symptoms:
- `COMPUTE_CONFIG_INVALID`
- `COMPUTE_CONFIG_TARGET_REQUIRED`
- `COMPUTE_CONFIG_TARGET_UNKNOWN`
- "Multiple compute config files found"
Fix:
- export `defineComputeConfig({ app: ... })` or `defineComputeConfig({ apps: ... })`
- define exactly one of `app` or `apps`
- remove unknown top-level keys
- pass a target for multi-app build/run commands, such as `app build web`
- pass an existing `apps` key for multi-app deploys, such as `app deploy api`
- for `nuxt`, `astro`, and `nestjs`, prefer strategy defaults unless a custom `build` override is intentional; current configs allow the override
- for `framework: "custom"`, set both `build.outputDirectory` and `build.entrypoint`
- when `build.outputDirectory` is set for a configurable framework, also set `build.entrypoint` if the framework needs a configured runtime entrypoint
Minimal recovery config:
```typescript
import { defineComputeConfig } from "@prisma/compute-sdk/config";
export default defineComputeConfig({
app: {
framework: "hono",
entry: "src/index.ts",
httpPort: 8080,
},
});
```
## `create-prisma --yes` Did Not Deploy
`--yes` skips prompts and does not opt into deploy. Pass `--deploy` explicitly:
```bash
bunx create-prisma@latest --name my-api --template hono --provider postgresql --deploy
```
If the integrated deploy cannot complete, scaffold succeeds but deploy should be reported as failed.
## Accidental Prisma Postgres Provisioning
With PostgreSQL, no `--database-url`, and no `--no-prisma-postgres`, setup can provision Prisma Postgres. For local smoke tests, pass:
```bash
--no-prisma-postgres --database-url "postgresql://USER:PASSWORD@HOST:PORT/DB"
```
Use a disposable real database URL if Prisma commands need to run.
## Auth Fails
Symptoms:
- `project list` fails
- `auth whoami` fails
- browser login was not completed
- commands use the wrong workspace after a second login
- another workspace is stored locally but commands behave signed out
- `PRISMA_SERVICE_TOKEN` is missing, empty, expired, or lacks workspace/project permissions
Fix:
```bash
bunx @prisma/cli@latest auth login
bunx @prisma/cli@latest auth whoami
bunx @prisma/cli@latest auth workspace list --json
```
If multiple local OAuth workspaces exist, switch explicitly. Prefer ids from JSON:
```bash
bunx @prisma/cli@latest auth workspace use <workspace-id>
bunx @prisma/cli@latest auth whoami --json
bunx @prisma/cli@latest project list --json
```
For a human terminal, `auth workspace use` with no argument opens an interactive picker or selects the only local OAuth workspace without prompting. In non-interactive or `--json` mode, use `auth workspace use <id-or-name>` instead.
If the active workspace was logged out or its token refresh failed, the CLI intentionally stays signed out for OAuth commands rather than falling through to another cached workspace. Recover by running `auth workspace list --json` and then `auth workspace use <workspace-id>`.
To remove only one local OAuth workspace session:
```bash
bunx @prisma/cli@latest auth workspace logout <workspace-id-or-name>
# or:
bunx @prisma/cli@latest auth logout --workspace <workspace-id-or-name>
```
Use plain `auth logout` only when you want to clear all local OAuth workspace sessions.
For CI, `@prisma/cli` can authenticate with `PRISMA_SERVICE_TOKEN`:
```bash
test -n "${PRISMA_SERVICE_TOKEN:-}" && echo "PRISMA_SERVICE_TOKEN is set"
bunx @prisma/cli@latest auth whoami
bunx @prisma/cli@latest app deploy --json --no-interactive --prod --yes --env .env
```
If `PRISMA_SERVICE_TOKEN` is set and non-empty, it is the active auth source and local OAuth workspace switching is unavailable for command execution. Unset `PRISMA_SERVICE_TOKEN` before using `auth workspace use` to change local OAuth workspace context.
If `PRISMA_SERVICE_TOKEN` is set but empty, the CLI errors before trying browser-login credentials. Unset it or provide a valid workspace service token. Never echo, log, or paste the token value; only check whether it is present.
Local storage hints for debugging:
- Override auth storage with `PRISMA_COMPUTE_AUTH_FILE` when isolating tests.
- Default macOS OAuth credential file: `~/Library/Application Support/prisma/auth.json`.
- Active workspace metadata sidecar: `~/Library/Application Support/prisma/auth.context.json`.
- Project binding: `.prisma/local.json`.
- Local app/project state: `.prisma/cli/state.json`, usually next to the discovered `prisma.compute.ts`.
Do not print credential files or token values into logs.
## Project Setup Fails
Symptoms:
- `PROJECT_SETUP_REQUIRED`
- non-interactive deploy cannot choose a Project
- deploy was expected to create a Project but did not
Fix:
```bash
bunx @prisma/cli@latest app deploy --project <id-or-name> --json --no-interactive
bunx @prisma/cli@latest app deploy --create-project <name> --yes
```
Do not rely on `--yes` alone to choose Project scope. `--project`, `--create-project`, and `PRISMA_PROJECT_ID` are mutually exclusive.
## Missing or Placeholder `DATABASE_URL`
Symptoms:
- Prisma Client throws `DATABASE_URL is required`
- migration scripts fail immediately
- deploy runs but app fails on database access
Fix:
1. Put a real production-ready `DATABASE_URL` in `.env` or project env.
2. Run `prisma generate`.
3. Run migrations with the project's `db:migrate` or production migration command.
4. Redeploy with `--env .env` or project env configured.
If Prisma Client generation or runtime env loading is the concrete failure, then inspect Prisma-specific config:
```bash
test -f prisma.config.ts && sed -n '1,160p' prisma.config.ts
test -f prisma/schema.prisma && sed -n '1,220p' prisma/schema.prisma
```
Never deploy `postgresql://USER:PASSWORD@HOST:PORT/DATABASE` placeholder values.
## Wrong Branch, Env, or Database
Symptoms:
- preview deploy reads production env
- branch deploy cannot find `DATABASE_URL`
- app is deployed to the expected branch but points at the wrong database
- logs are inspected for the current app while the failing URL belongs to a different deployment id
Check:
```bash
bunx @prisma/cli@latest project show --json
bunx @prisma/cli@latest project env list --role production --json
bunx @prisma/cli@latest project env list --role preview --json
bunx @prisma/cli@latest project env list --branch feature/foo --json
bunx @prisma/cli@latest app list-deploys --json
bunx @prisma/cli@latest app logs --deployment <deployment-id> --json
```
Fix:
- pass the same `--branch <git-name>` to `app deploy`, `database create`, and branch-specific `project env` commands
- use `--role production` for production env and `--role preview` for preview-template env
- capture the deployment id and URL from deploy JSON, then inspect logs with `app logs --deployment <deployment-id>`
- `app show`, `app list-deploys`, and `app logs` do not filter by branch; capture and use the deployment id
- treat `app promote <deployment-id>` as a production action because it rebuilds with production env vars
- do not expect `prisma.compute.ts` to select Project, Branch, production, or database scope; it only supplies app deploy defaults
## Database Wiring or Schema Did Not Apply
Symptoms:
- deploy runs but the app cannot find `DATABASE_URL`
- database env vars exist but the database is empty
- a deploy-all run points multiple apps at the same branch database
Fix:
- read [`app-deploy-cli.md`](app-deploy-cli.md) `Database and Env` for the database/env guardrails
- create and assign database env vars explicitly for the intended branch/app scope
- run migrations, seed, or schema push yourself after database setup; Compute never applies schema changes for you
- for multi-app deploy-all with app-specific database isolation, create and assign those database env vars explicitly before deploy
## Workspace plan limit reached
When the installed CLI returns `PLAN_LIMIT_REACHED`, treat it as a workspace plan restriction rather than a Compute or database outage.
For agent/CI handling, run the relevant database command with `--json` and branch on `error.code === "PLAN_LIMIT_REACHED"`. Read `error.meta.upgradeUrl`, `planName`, `workspaceId`, and `usageBlocked`; optional values may be `null`. This is a workspace plan restriction rather than a Compute/database outage. Use the canonical upgrade URL when returned or direct the user to Prisma Console. Do not retry as an outage or infer a plan limit from status codes or message text.
## Next.js Standalone Missing
Error shape:
```text
Next.js build did not produce standalone output
```
Fix `next.config.ts`:
```typescript
const nextConfig = {
output: "standalone",
}
export default nextConfig
```
Then reinstall/build if needed and deploy again.
## Next.js dependency missing after a successful build
Symptoms in pnpm/Bun isolated workspaces can include a deployment that builds successfully but exits before useful runtime logs, often with `Cannot find module` for `styled-jsx` or another traced dependency.
The current Compute SDK preserves in-artifact package-store symlinks and materializes only safe out-of-tree targets when staging Next standalone output. Do not manually flatten or rewrite `.next/standalone/node_modules` symlinks; that can break the isolated-store layout.
Fix:
1. Upgrade `@prisma/compute-sdk` and `@prisma/cli` to current versions.
2. Remove only the generated build artifact/cache appropriate to the project, then rebuild.
3. Confirm `output: "standalone"`, redeploy, and inspect the new deployment logs.
4. If it persists, report the package manager, workspace layout, first missing module, and SDK/CLI versions through `@prisma/cli feedback` without secrets.
## Nitro Entry Missing
Nuxt or TanStack Start error shape:
```text
.output/server/index.mjs
```
General fix:
- ensure the correct framework plugins are installed
- run the framework build locally
- avoid custom Nitro presets that produce a non-Node target
- use the default Nitro node server preset
For TanStack Start specifically:
- keep `nitro` in `dependencies`
- keep `import { nitro } from "nitro/vite"` in `vite.config.ts`
- keep `plugins: [tanstackStart(), nitro(), viteReact()]` or the framework-equivalent plugin order
- run `bun run build` and verify `.output/server/index.mjs` exists
- do not replace the production server with `vite preview`
Compute detection selects TanStack Start when it sees `@tanstack/react-start` or `@tanstack/solid-start`. If the Nitro entrypoint is missing after that, fix the TanStack/Nitro build output; do not assume Compute will silently use a Bun deployment.
## Bun Entrypoint Missing
Error shape:
```text
Entrypoint is required
Entrypoint file does not exist
```
Fix either:
```json
{
"main": "src/index.ts"
}
```
or deploy with:
```bash
bunx @prisma/cli@latest app deploy --framework bun --entry src/index.ts
```
## Port Mismatch
Symptoms:
- deploy succeeds but the app is unreachable
- health checks fail
- logs show the server listening on a different port
Fix:
- read `process.env.PORT`
- pass `--http-port <port>` when the app has a fixed port
- use the generated `compute:deploy` script when it exists
- remember the `@prisma/cli app deploy` default is HTTP `3000`; generated Hono/Elysia projects usually configure `8080` through `prisma.compute.ts` or flag-backed `--http-port 8080` scripts
- use the template defaults: Hono/Elysia `8080`, Next/TanStack/Nuxt `3000`, Astro `4321`
## Public URL Smoke Test Fails
Symptoms:
- deploy command completed
- `app show` or deploy output has a URL
- the public URL times out, returns 5xx, or returns an unexpected page
Check:
```bash
curl -i https://<deployment-url>
curl -i https://<deployment-url>/health
bunx @prisma/cli@latest app logs --json
```
Fix by following the first concrete failure:
- connection timeout or 5xx: check logs, host binding, and port mapping
- unexpected status or body: verify the route path and app framework output
- local URL tested by mistake: rerun against the public deployment URL, not `localhost` or `127.0.0.1`
## Localhost Binding
Symptoms:
- deploy says the app started or the port was observed, but the public URL is unreachable
- logs show a server listening on `localhost` or `127.0.0.1`
- `app run` works locally, but the deployed app cannot receive external traffic
Why this happens:
Compute's boot watcher polls `/proc/net/tcp` and `/proc/net/tcp6` for configured ports entering `LISTEN`. That readiness signal tracks the port, not whether the app bound `127.0.0.1` or all interfaces. A loopback-only listener can therefore look ready while public ingress still cannot reach it.
Fix:
- remove hard-coded `localhost` or `127.0.0.1` server host settings
- bind on `0.0.0.0` or the framework equivalent, such as Astro `server.host: true`
- for Next.js standalone, do not deploy with `HOSTNAME=localhost`; use `HOSTNAME=0.0.0.0` if the host is overridden
- keep port and host fixes together: `0.0.0.0:<deployed-http-port>`
## Env Changes Did Not Apply
Generated `compute:deploy` scripts redeploy using the generated flags and/or `prisma.compute.ts`; they do not run migrations or seed data.
After env changes:
```bash
bunx @prisma/cli@latest project env list
bunx @prisma/cli@latest project env list --branch feature/foo
bunx @prisma/cli@latest app deploy --prod --yes --env .env
bunx @prisma/cli@latest app deploy --branch feature/foo --env .env.preview
```
If using branch-specific env, confirm the branch name and role.
## Need Logs
Runtime logs for the current app:
```bash
bunx @prisma/cli@latest app logs
```
Specific deployment:
```bash
bunx @prisma/cli@latest app logs --deployment <deployment-id>
```
Machine-readable:
```bash
bunx @prisma/cli@latest app logs --json
```
Build logs for GitHub/Console builds:
```bash
bunx @prisma/cli@latest build logs <build-id>
bunx @prisma/cli@latest build logs <build-id> --follow
bunx @prisma/cli@latest build logs <build-id> --json
```
Use `build logs` for build output keyed by a Build id from a GitHub check run, Console build page, or Management API build record. Use `app logs` for runtime logs keyed by the current app deployment or a deployment id.
Summarize relevant errors. Do not paste secrets.
## Report Unresolved CLI Issues
When a CLI failure survives the checks above, or a command crashes with `UNEXPECTED_ERROR`, report it to the Prisma team:
```bash
bunx @prisma/cli@latest feedback "app deploy crashed: <first error line>"
```
Prefer the pre-filled command from a `--json` crash envelope's `nextActions` verbatim. Anonymous; never put secrets, connection URLs, or tokens in the message.

View File

@ -0,0 +1,192 @@
---
name: prisma-database-setup
description: Guides for configuring Prisma with different database providers (PostgreSQL, MySQL, SQLite, MongoDB, etc.). Use when setting up a new project, changing databases, or troubleshooting connection issues. Triggers on "configure postgres", "connect to mysql", "setup mongodb", "sqlite setup".
license: MIT
metadata:
author: prisma
version: "7.6.0"
---
# Prisma Database Setup
Comprehensive guides for configuring Prisma ORM with various database providers.
## When to Apply
Reference this skill when:
- Initializing a new Prisma project
- Switching database providers
- Configuring connection strings and environment variables
- Troubleshooting database connection issues
- Setting up database-specific features
- Generating and instantiating Prisma Client
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Provider Guides | CRITICAL | provider names |
| 2 | Prisma Postgres | HIGH | `prisma-postgres` |
| 3 | Client Setup | CRITICAL | `prisma-client-setup` |
## System Prerequisites
- **Node.js 20.19.0+**
- **TypeScript 5.4.0+**
## Bun Runtime
If you're using Bun, run Prisma CLI commands with `bunx --bun prisma ...` so Prisma uses the Bun runtime instead of falling back to Node.js.
## Supported Databases
| Database | Provider String | Notes |
|----------|-----------------|-------|
| PostgreSQL | `postgresql` | Default, full feature support |
| MySQL | `mysql` | Widespread support, some JSON diffs |
| SQLite | `sqlite` | Local file-based, no enum/scalar lists |
| MongoDB | `mongodb` | Mongo-specific workflow; do not apply SQL driver-adapter guidance |
| SQL Server | `sqlserver` | Microsoft ecosystem |
| CockroachDB | `cockroachdb` | Distributed SQL, Postgres-compatible |
| Prisma Postgres | `postgresql` | Managed serverless database |
## Configuration Files
Your configuration shape depends on the provider and Prisma major version:
1. **All providers** use **`prisma/schema.prisma`**.
2. **Prisma 7 SQL setups** typically use **`prisma.config.ts`** for datasource URLs.
3. **MongoDB projects should stay on Prisma 6.x**, keep `url = env("DATABASE_URL")` in the schema, and continue using the classic MongoDB setup.
## Driver Adapters
The standard SQL workflow uses a driver adapter. Choose the adapter and driver for your database and pass the adapter to `PrismaClient`.
| Database | Adapter | JS Driver |
|----------|---------|-----------|
| PostgreSQL | `@prisma/adapter-pg` | `pg` |
| CockroachDB | `@prisma/adapter-pg` | `pg` |
| Prisma Postgres (Node.js) | `@prisma/adapter-pg` | `pg` |
| Prisma Postgres (edge/serverless) | `@prisma/adapter-ppg` | `@prisma/ppg` |
| MySQL / MariaDB | `@prisma/adapter-mariadb` | `mariadb` |
| SQLite | `@prisma/adapter-better-sqlite3` | `better-sqlite3` |
| SQLite (Turso/LibSQL) | `@prisma/adapter-libsql` | `@libsql/client` |
| SQL Server | `@prisma/adapter-mssql` | `node-mssql` |
MongoDB should not follow the Prisma 7 SQL adapter workflow. Use the latest Prisma 6.x release for MongoDB projects and do not install a SQL `@prisma/adapter-*` package for it.
Example (PostgreSQL):
```ts
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
## Prisma Client Setup (Required)
Prisma Client must be installed and generated for any database.
1. Install Prisma CLI and Prisma Client:
```bash
npm install prisma --save-dev
npm install @prisma/client
```
1. Add a generator block (`prisma-client` requires an explicit output path):
```prisma
generator client {
provider = "prisma-client"
output = "../generated"
}
```
1. Generate Prisma Client:
```bash
npx prisma generate
```
1. For SQL providers, instantiate Prisma Client with the database-specific driver adapter:
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
1. Re-run `prisma generate` after every schema change.
## Quick Reference
### PostgreSQL
```prisma
datasource db {
provider = "postgresql"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
### MySQL
```prisma
datasource db {
provider = "mysql"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
### SQLite
```prisma
datasource db {
provider = "sqlite"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
### MongoDB
```prisma
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
```
For MongoDB, stay on the latest Prisma 6.x line and keep the connection URL in `schema.prisma`. Do not move a MongoDB project to the Prisma 7 SQL adapter setup. If a MongoDB project asks about upgrading Prisma versions, route to the `prisma-mongodb-upgrade` skill (stay-on-v6 vs Prisma Next is the real decision; Prisma 7 is not an option).
## Rule Files
See individual rule files for detailed setup instructions:
```
references/postgresql.md
references/mysql.md
references/sqlite.md
references/mongodb.md
references/sqlserver.md
references/cockroachdb.md
references/prisma-postgres.md
references/prisma-client-setup.md
```
## How to Use
Choose the provider reference file for your database, then apply `references/prisma-client-setup.md` to complete client generation and adapter setup. For MongoDB, use `references/mongodb.md` instead of copying the SQL adapter examples or Prisma 7 config pattern.

View File

@ -0,0 +1,89 @@
# CockroachDB Setup
Configure Prisma with CockroachDB.
## Prerequisites
- CockroachDB cluster
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "cockroachdb"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## 3. Environment Variable
In `.env`:
```env
DATABASE_URL="postgresql://user:password@host:26257/db?sslmode=verify-full"
```
Note: CockroachDB uses the PostgreSQL wire protocol, so the URL often looks like postgresql, but the provider **MUST** be `cockroachdb` in the schema to handle specific CRDB features correctly.
## Driver Adapter
Use a driver adapter for the standard SQL workflow. CockroachDB is PostgreSQL-compatible, so use the PostgreSQL adapter.
1. Install adapter and driver:
```bash
npm install @prisma/adapter-pg pg
```
2. Instantiate Prisma Client with the adapter:
```typescript
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
## ID Generation
CockroachDB uses `BigInt` or `UUID` for IDs efficiently.
```prisma
model User {
id BigInt @id @default(autoincrement()) // Uses unique_rowid()
}
```
Or using string UUIDs:
```prisma
model User {
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
}
```
## Common Issues
### Schema Introspection
Always use `provider = "cockroachdb"` to ensure correct type mapping during `db pull`.

View File

@ -0,0 +1,90 @@
# MongoDB Setup
MongoDB projects should stay on the latest Prisma 6.x release. Do not upgrade a MongoDB app to Prisma 7's SQL client path.
## Prerequisites
- MongoDB 4.2+
- Replica Set configured (required for transactions)
- Latest Prisma 6.x release, or your team's pinned Prisma 6 version
- Node.js 20.19.0+
- TypeScript 5.4.0+
## 1. Schema Configuration
Use the standard Prisma 6 MongoDB setup with `prisma-client-js`.
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
```
### Driver Adapters
Do **not** apply the Prisma 7 SQL adapter setup here. MongoDB does not use a SQL `@prisma/adapter-*` package.
### ID Field Requirement
MongoDB models **must** have a mapped `_id` field using `@id` and `@map("_id")`, usually of type `String` with `auto()` and `db.ObjectId`.
```prisma
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
name String?
}
```
### Relations
Relations in MongoDB expect IDs to be `db.ObjectId` type.
```prisma
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
author User @relation(fields: [authorId], references: [id])
authorId String @db.ObjectId
}
```
## 2. Environment Variable
In `.env`:
```env
DATABASE_URL="mongodb+srv://user:password@cluster.mongodb.net/mydb?retryWrites=true&w=majority"
```
## Migrations vs Introspection
- **No Migrations**: MongoDB is schema-less. `prisma migrate` commands **do not work**.
- **db push**: Use `prisma db push` to sync indexes and constraints.
- **db pull**: Use `prisma db pull` to generate schema from existing data (sampling).
## Current Verification Notes
- `prisma init --datasource-provider mongodb` is still implemented in Prisma's CLI source.
- Prisma's upstream repo still contains MongoDB fixtures and tests.
- Local verification shows Prisma 7 can still recognize MongoDB inputs, but the generated client path does not provide a supported MongoDB upgrade path.
- Local verification shows Prisma 6.x works end to end with `prisma-client-js`, `prisma db push`, and `new PrismaClient()` against a MongoDB replica set.
## Version Guidance
- For MongoDB, stay on the latest available Prisma 6.x release.
- Treat Prisma 7 MongoDB migration attempts as unsupported until Prisma ships a real MongoDB upgrade path.
## Common Issues
### "Transactions not supported"
Ensure your MongoDB instance is a **Replica Set**. Standalone instances do not support transactions. Atlas clusters are replica sets by default.
### "Invalid ObjectID"
Ensure fields referencing IDs are decorated with `@db.ObjectId` if the target is an ObjectID.

View File

@ -0,0 +1,126 @@
# MySQL Setup
Configure Prisma with MySQL (or MariaDB).
## Prerequisites
- MySQL or MariaDB database
- Connection string
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "mysql"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## 3. Environment Variable
In `.env`:
```env
DATABASE_URL="mysql://user:password@localhost:3306/mydb"
```
### Connection String Format
```
mysql://USER:PASSWORD@HOST:PORT/DATABASE
```
- **USER**: Database user
- **PASSWORD**: Password
- **HOST**: Hostname
- **PORT**: Port (default 3306)
- **DATABASE**: Database name
## Driver Adapter
Use a driver adapter for the standard SQL workflow.
1. Install adapter and driver:
```bash
npm install @prisma/adapter-mariadb mariadb
```
2. Instantiate Prisma Client with the adapter:
```typescript
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaMariaDb } from '@prisma/adapter-mariadb'
const adapter = new PrismaMariaDb({
host: 'localhost',
port: 3306,
connectionLimit: 5,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
})
const prisma = new PrismaClient({ adapter })
```
### Text protocol option
If you need the MariaDB driver's text protocol instead of the default binary `execute()` path, enable `useTextProtocol` explicitly:
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaMariaDb } from '@prisma/adapter-mariadb'
const adapter = new PrismaMariaDb(process.env.DATABASE_URL!, {
useTextProtocol: true,
})
const prisma = new PrismaClient({ adapter })
```
Use this only when you specifically need text-protocol compatibility for your MariaDB setup.
## PlanetScale Setup
PlanetScale uses MySQL but requires specific settings because it doesn't support foreign key constraints.
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "mysql"
relationMode = "prisma" // Emulate foreign keys in Prisma
}
```
## Common Issues
### "Too many connections"
MySQL has a connection limit. Adjust connection pool size in URL:
```env
DATABASE_URL="mysql://...?connection_limit=5"
```
### JSON Support
MySQL 5.7+ supports JSON. MariaDB 10.2+ supports JSON (as an alias for LONGTEXT with check constraints). Prisma handles this, but verify your version.

View File

@ -0,0 +1,92 @@
# PostgreSQL Setup
Configure Prisma with PostgreSQL.
## Prerequisites
- PostgreSQL database (local or cloud)
- Connection string
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "postgresql"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## 3. Environment Variable
In `.env`:
```env
DATABASE_URL="postgresql://user:password@localhost:5432/mydb?schema=public"
```
### Connection String Format
```
postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=SCHEMA
```
- **USER**: Database user
- **PASSWORD**: Password (URL encoded if special chars)
- **HOST**: Hostname (localhost, IP, or domain)
- **PORT**: Port (default 5432)
- **DATABASE**: Database name
- **SCHEMA**: Schema name (default `public`)
## Driver Adapter
Use a driver adapter for the standard SQL workflow.
1. Install adapter and driver:
```bash
npm install @prisma/adapter-pg pg
```
2. Instantiate Prisma Client with the adapter:
```typescript
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
## Common Issues
### "Can't reach database server"
- Check host and port
- Check firewall settings
- Ensure database is running
### "Authentication failed"
- Check user/password
- Special characters in password must be URL-encoded
### "Schema does not exist"
- Ensure `?schema=public` (or your schema) is in the URL

View File

@ -0,0 +1,47 @@
# Prisma Client Setup
Generate and instantiate Prisma Client for Prisma's standard SQL provider workflow. For MongoDB, follow the provider-specific notes in `references/mongodb.md` instead of copying the SQL adapter example below.
## 1. Install dependencies
```bash
npm install prisma --save-dev
npm install @prisma/client
```
## 2. Add generator block
In `prisma/schema.prisma`:
```prisma
generator client {
provider = "prisma-client"
output = "../generated"
}
```
`prisma-client` requires an explicit `output` path and does not generate into `node_modules` by default.
## 3. Generate Prisma Client
```bash
npx prisma generate
```
Re-run `prisma generate` after every schema change to keep the client in sync.
## 4. Instantiate Prisma Client
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
If you change the generator `output`, update the import path to match. For the SQL provider workflow, replace `PrismaPg` with the adapter for your database.
## 5. Use a single instance
Each `PrismaClient` instance creates a connection pool. Reuse a single instance per app process to avoid exhausting database connections.

View File

@ -0,0 +1,130 @@
# Prisma Postgres Setup
Configure Prisma with Prisma Postgres (Managed).
## Overview
Prisma Postgres is a serverless, managed PostgreSQL database optimized for Prisma.
## Setup via CLI
You can provision a Prisma Postgres instance directly via the CLI:
```bash
prisma init --db
```
This will:
1. Log you into Prisma Data Platform.
2. Create a new project and database instance.
3. Update your `.env` with the connection string.
## Connection String
For Prisma CLI flows and Accelerate-style usage, you may see a `prisma+postgres://` URL.
For Prisma Client with a driver adapter in Node.js, prefer the direct TCP connection string from the Prisma Postgres dashboard:
```env
DATABASE_URL="postgres://identifier:key@db.prisma.io:5432/postgres?sslmode=require"
```
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "postgresql" // Use postgresql provider
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Driver Adapter
Use a driver adapter for Prisma Postgres in the standard SQL workflow.
### Recommended for standard Node.js apps
1. Install adapter and driver:
```bash
npm install @prisma/adapter-pg pg
```
2. Use the direct TCP connection string from Prisma Console:
```typescript
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
```
`PrismaPg` also accepts the connection string directly:
```typescript
const adapter = new PrismaPg(process.env.DATABASE_URL!)
const prisma = new PrismaClient({ adapter })
```
For PostgreSQL prepared statement naming, pass adapter options as the second argument:
```typescript
import { createHash } from 'node:crypto'
const adapter = new PrismaPg(process.env.DATABASE_URL!, {
statementNameGenerator: ({ sql }) =>
`prisma_${createHash('sha1').update(sql).digest('hex').slice(0, 16)}`,
})
```
### Edge/serverless option
Use the Prisma Postgres serverless driver only when you need HTTP/WebSocket transport in environments like Workers or Edge Functions:
```bash
npm install @prisma/adapter-ppg @prisma/ppg
```
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPostgresAdapter } from '@prisma/adapter-ppg'
const prisma = new PrismaClient({
adapter: new PrismaPostgresAdapter({
connectionString: process.env.PRISMA_DIRECT_TCP_URL,
}),
})
```
This serverless driver is the specialized path for HTTP/WebSocket-based edge and serverless runtimes, not the default recommendation for standard Node.js apps.
## Features
- **Serverless**: Scales to zero.
- **Caching**: Integrated query caching (Accelerate).
- **Real-time**: Database events (Pulse).
## Using with Prisma Client
Use the Prisma Postgres adapter shown above when instantiating Prisma Client.

View File

@ -0,0 +1,106 @@
# SQLite Setup
Configure Prisma with SQLite.
## Prerequisites
- None (file-based)
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "sqlite"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## 3. Environment Variable
In `.env`:
```env
DATABASE_URL="file:./dev.db"
```
### Connection String Format
```
file:PATH
```
- **PATH**: Relative path to the database file. Check `prisma.config.ts` if you need to confirm how your app resolves it.
## Driver Adapter
Use a driver adapter for the standard SQL workflow.
1. Install adapter and driver:
```bash
npm install @prisma/adapter-better-sqlite3 better-sqlite3
```
2. Instantiate Prisma Client with the adapter:
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3'
const adapter = new PrismaBetterSqlite3({
url: process.env.DATABASE_URL ?? 'file:./dev.db',
})
const prisma = new PrismaClient({ adapter })
```
## Using Driver Adapter (LibSQL / Turso)
For edge compatibility or Turso:
1. Install:
```bash
npm install @prisma/adapter-libsql @libsql/client
```
2. Instantiate:
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaLibSql } from '@prisma/adapter-libsql'
const adapter = new PrismaLibSql({
url: process.env.TURSO_DATABASE_URL,
authToken: process.env.TURSO_AUTH_TOKEN,
})
const prisma = new PrismaClient({ adapter })
```
## Limitations
- **No Enums**: SQLite doesn't support enums (Prisma polyfills them or treats as String).
- **No Scalar Lists**: `String[]` is not supported directly.
- **Concurrency**: Write operations lock the file.
## Common Issues
### "Database file not found"
Ensure the path in `DATABASE_URL` is correct relative to where Prisma is running or the schema file. `file:./dev.db` creates it next to schema.

View File

@ -0,0 +1,94 @@
# SQL Server Setup
Configure Prisma with Microsoft SQL Server.
## Prerequisites
- SQL Server 2017, 2019, 2022, or Azure SQL
- TCP/IP enabled
## 1. Schema Configuration
In `prisma/schema.prisma`:
```prisma
datasource db {
provider = "sqlserver"
}
generator client {
provider = "prisma-client"
output = "../generated"
}
```
## 2. Config Configuration
In `prisma.config.ts`:
```typescript
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
datasource: {
url: env('DATABASE_URL'),
},
})
```
## 3. Environment Variable
In `.env`:
```env
DATABASE_URL="sqlserver://localhost:1433;database=mydb;user=sa;password=Password123;encrypt=true;trustServerCertificate=true"
```
### Connection String Format
```
sqlserver://HOST:PORT;database=DB;user=USER;password=PASS;encrypt=true;trustServerCertificate=true
```
- **encrypt**: Required for Azure (true).
- **trustServerCertificate**: True for self-signed certs (local dev).
## Driver Adapter
Use a driver adapter for the standard SQL workflow.
1. Install adapter and driver:
```bash
npm install @prisma/adapter-mssql mssql
```
2. Instantiate Prisma Client with the adapter:
```typescript
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaMssql } from '@prisma/adapter-mssql'
const adapter = new PrismaMssql({
server: 'localhost',
port: 1433,
database: 'mydb',
user: process.env.SQLSERVER_USER,
password: process.env.SQLSERVER_PASSWORD,
options: {
encrypt: true,
trustServerCertificate: true,
},
})
const prisma = new PrismaClient({ adapter })
```
## Common Issues
### "Login failed for user"
- SQL Server auth vs Windows auth. Prisma typically uses SQL Server authentication (username/password).
- Ensure TCP/IP is enabled in SQL Server Configuration Manager.
### "Table not found" (dbo schema)
Prisma assumes `dbo` schema by default. If using another schema, update the model or connection string? SQL Server provider mostly sticks to default schema.

View File

@ -0,0 +1,270 @@
---
name: prisma-driver-adapter-implementation
description: Required reference for Prisma ORM 7 SQL driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter, Transaction, savepoint, result mapping, or DriverAdapterError behavior. Covers current transaction lifecycle, optional savepoint hooks, original database-error preservation, and verification.
license: MIT
metadata:
author: prisma
version: "7.9.1"
---
# Prisma SQL Driver Adapter Implementation
Use this guide with the exact `@prisma/driver-adapter-utils` version installed by the target Prisma release. Driver adapters are a protocol boundary: type-compatible code can still corrupt values, leak connections, or break transactions.
## When to Apply
- Implementing `SqlDriverAdapterFactory`, `SqlMigrationAwareDriverAdapterFactory`, `SqlDriverAdapter`, or `Transaction`
- Adding nested-transaction/savepoint support
- Mapping driver values, column metadata, bind arguments, or database errors
- Debugging `P2039`, transaction leaks, shadow-database failures, or adapter-specific query behavior
## Contract snapshot
```typescript
interface SqlDriverAdapterFactory extends AdapterInfo {
connect(): Promise<SqlDriverAdapter>
}
interface SqlMigrationAwareDriverAdapterFactory extends SqlDriverAdapterFactory {
connectToShadowDb(): Promise<SqlDriverAdapter>
}
interface SqlDriverAdapter extends AdapterInfo {
queryRaw(query: SqlQuery): Promise<SqlResultSet>
executeRaw(query: SqlQuery): Promise<number>
executeScript(script: string): Promise<void>
startTransaction(isolationLevel?: IsolationLevel): Promise<Transaction>
getConnectionInfo?(): ConnectionInfo
dispose(): Promise<void>
}
interface Transaction extends AdapterInfo {
readonly options: { usePhantomQuery: boolean }
queryRaw(query: SqlQuery): Promise<SqlResultSet>
executeRaw(query: SqlQuery): Promise<number>
commit(): Promise<void>
rollback(): Promise<void>
createSavepoint?(name: string): Promise<void>
rollbackToSavepoint?(name: string): Promise<void>
releaseSavepoint?(name: string): Promise<void>
}
```
`IsolationLevel` currently includes `READ UNCOMMITTED`, `READ COMMITTED`, `REPEATABLE READ`, `SNAPSHOT`, and `SERIALIZABLE`; validate what the concrete database supports.
## Priority rules
| Priority | Rule | Impact |
|----------|------|--------|
| CRITICAL | One dedicated connection per transaction | Prevents interleaving and leaks |
| CRITICAL | `commit`/`rollback` are lifecycle cleanup hooks | Prevents duplicate COMMIT/ROLLBACK |
| CRITICAL | Savepoints live on `Transaction`, not adapter-global depth | Makes nested scopes connection-local |
| CRITICAL | Preserve original database error code/message | Enables useful `P2039` fallback |
| HIGH | Map arguments and result metadata exactly | Prevents silent value corruption |
| HIGH | Shadow databases are isolated and always cleaned up | Makes Migrate safe |
| HIGH | Dispose only resources the adapter owns | Prevents shutting down caller-owned pools |
## Query implementation
`SqlQuery` contains `sql`, `args`, and parallel `argTypes`. Map each argument using both value and `ArgType`; do not discard type/arity information. Execute in the driver's array/tuple row mode so column order is stable.
```typescript
class ExampleQueryable {
readonly provider = 'postgres' as const
readonly adapterName = '@acme/adapter-example'
constructor(protected readonly connection: DriverConnection) {}
async queryRaw(query: SqlQuery): Promise<SqlResultSet> {
try {
const result = await this.connection.query({
text: query.sql,
values: query.args.map((value, index) =>
mapArg(value, query.argTypes[index]),
),
rowMode: 'array',
})
return {
columnNames: result.fields.map((field) => field.name),
columnTypes: result.fields.map(mapColumnType),
rows: result.rows,
}
} catch (error) {
throwAdapterError(error)
}
}
async executeRaw(query: SqlQuery): Promise<number> {
try {
const result = await this.connection.execute(
query.sql,
query.args.map((value, index) => mapArg(value, query.argTypes[index])),
)
return result.rowsAffected ?? 0
} catch (error) {
throwAdapterError(error)
}
}
}
```
### Result mapping
Return `columnNames`, `columnTypes`, and `rows` with identical lengths/order. Map driver metadata to `ColumnTypeEnum` deliberately:
- signed integer widths to `Int32`/`Int64`; preserve 64-bit values without JS number truncation
- decimal/numeric to `Numeric` using the representation expected by Prisma
- binary to `Uint8Array`/`Bytes`
- date-only, time-only, and timestamp to `Date`, `Time`, and `DateTime`
- UUID, JSON, enum, arrays, and provider-specific unknown values to their explicit types
- unsupported native types to `DriverAdapterError({ kind: 'UnsupportedNativeDataType', type })`
Test `null`, empty arrays, array element types, big integers, decimals, byte arrays, JSON, dates, and user-defined/unknown native types.
### Script execution
`executeScript` must execute a migration script as the provider expects. Prefer the driver's native multi-statement/script facility or a real SQL parser. Naively splitting on `;` breaks functions, triggers, quoted strings, and dialect-specific blocks.
## Transaction protocol
`startTransaction` must acquire one dedicated connection, start the database transaction, apply the requested isolation level, and return a `Transaction` bound to that same connection. If setup fails, release it immediately.
```typescript
async startTransaction(level?: IsolationLevel): Promise<Transaction> {
const connection = await this.pool.acquire()
try {
const tx = new ExampleTransaction(connection, () => connection.release())
await tx.executeRaw({ sql: 'BEGIN', args: [], argTypes: [] })
if (level) {
await tx.executeRaw({
sql: `SET TRANSACTION ISOLATION LEVEL ${validateLevel(level)}`,
args: [],
argTypes: [],
})
}
return tx
} catch (error) {
connection.release(error)
throwAdapterError(error)
}
}
```
### Commit and rollback
Prisma coordinates the SQL `COMMIT`/`ROLLBACK` through `executeRaw`. The transaction object's `commit()` and `rollback()` methods are lifecycle hooks: detach listeners and release the dedicated connection exactly once. They must not issue a second SQL commit/rollback.
```typescript
class ExampleTransaction extends ExampleQueryable implements Transaction {
readonly options = { usePhantomQuery: false }
#closed = false
constructor(connection: DriverConnection, private readonly release: () => void) {
super(connection)
}
async commit() { this.finish() }
async rollback() { this.finish() }
private finish() {
if (this.#closed) return
this.#closed = true
this.release()
}
async createSavepoint(name: string) {
await this.control(`SAVEPOINT ${safeSavepoint(name)}`)
}
async rollbackToSavepoint(name: string) {
await this.control(`ROLLBACK TO SAVEPOINT ${safeSavepoint(name)}`)
}
async releaseSavepoint(name: string) {
await this.control(`RELEASE SAVEPOINT ${safeSavepoint(name)}`)
}
private async control(sql: string) {
await this.executeRaw({ sql, args: [], argTypes: [] })
}
}
```
Implement the optional savepoint methods only where the provider supports them. Validate/quote savepoint identifiers. For providers whose savepoints are intentionally no-ops, document and test that limitation.
Never keep transaction depth on the shared adapter. Parallel transactions make adapter-global depth incorrect; nested state belongs to the returned transaction connection and Prisma's savepoint calls.
## Error mapping
Wrap recognized driver failures in `DriverAdapterError`. Map known conditions to `MappedError` kinds such as constraint violations, authentication/reachability, missing table/column/database, timeouts, closed transactions, invalid input, value range, and write conflicts.
For database errors, preserve `originalCode` and `originalMessage` even when falling back to the provider-specific raw variant:
```typescript
import {
DriverAdapterError,
type Error as DriverAdapterErrorObject,
type MappedError,
} from '@prisma/driver-adapter-utils'
function convertDriverError(error: DatabaseError): DriverAdapterErrorObject {
return {
originalCode: String(error.code),
originalMessage: error.message,
...mapKnownOrRaw(error),
}
}
function mapKnownOrRaw(error: DatabaseError): MappedError {
if (error.code === '23505') {
return { kind: 'UniqueConstraintViolation', constraint: parsedConstraint(error) }
}
return {
kind: 'postgres',
code: String(error.code ?? 'N/A'),
severity: error.severity ?? 'N/A',
message: error.message,
detail: error.detail,
column: error.column,
hint: error.hint,
}
}
function throwAdapterError(error: unknown): never {
if (!isDatabaseError(error)) throw error
throw new DriverAdapterError(convertDriverError(error))
}
```
Prisma uses preserved original details when an unmapped driver error becomes `P2039`. Do not replace every unknown exception with a fabricated `GenericJs` id; rethrow genuinely unexpected non-driver errors so programming bugs remain visible.
## Factory, ownership, and shadow database
- `connect()` returns a fresh usable adapter connection/pool wrapper.
- Track whether the factory created the pool. `dispose()` closes owned pools and only detaches listeners from caller-owned pools unless an explicit option transfers ownership.
- Implement `SqlMigrationAwareDriverAdapterFactory` only when `connectToShadowDb()` can create an isolated shadow database, connect to it, and drop it during disposal/failure cleanup.
- Never point the shadow adapter at the primary database. Quote generated identifiers and use cryptographically unique names.
- `getConnectionInfo()` should accurately report `schemaName`, `maxBindValues` when applicable, and `supportsRelationJoins`.
## Verification checklist
- [ ] Typecheck against the exact target `@prisma/driver-adapter-utils` version
- [ ] `queryRaw` preserves column order, types, nulls, and precision
- [ ] `executeRaw` reports affected rows correctly
- [ ] `executeScript` handles provider-specific multi-statement syntax
- [ ] Concurrent interactive transactions use distinct dedicated connections
- [ ] Success commits and releases once; failure rolls back and releases once
- [ ] Nested transaction tests exercise create/rollback/release savepoint hooks
- [ ] Unsupported isolation levels fail as `InvalidIsolationLevel`
- [ ] Known constraints map to structured errors
- [ ] Unmapped database errors retain original code/message and surface useful `P2039`
- [ ] Dispose ownership is tested for internal and external pools
- [ ] Shadow database creation, use, failure cleanup, and disposal are isolated
- [ ] Run Prisma Client integration/E2E tests, not only adapter unit tests
## Source references
- [Driver adapter interfaces](https://github.com/prisma/prisma/blob/v7/packages/driver-adapter-utils/src/types.ts)
- [PostgreSQL adapter transaction implementation](https://github.com/prisma/prisma/blob/v7/packages/adapter-pg/src/pg.ts)
- [PostgreSQL adapter error mapping](https://github.com/prisma/prisma/blob/v7/packages/adapter-pg/src/errors.ts)

View File

@ -0,0 +1,92 @@
---
name: prisma-mongodb-upgrade
description: Decision and migration guide for Prisma ORM MongoDB projects on v6, which have no upgrade path to v7. Use when a MongoDB project asks about upgrading Prisma, when "upgrade to prisma 7" comes up in a project with provider = "mongodb", or when evaluating a move to Prisma Next. Triggers on "upgrade prisma mongodb", "prisma 7 mongodb", "mongodb prisma migration", "prisma next mongodb".
license: MIT
metadata:
author: prisma
version: "0.1.0"
---
# Prisma MongoDB Upgrade Path
MongoDB projects are the one Prisma cohort with no road into Prisma 7: **v6 is the terminal
classic-ORM major for MongoDB, and v7 never ships a MongoDB connector**. The successor path
is [Prisma Next](https://github.com/prisma/prisma-next), where MongoDB support is in Early
Access with GA planned after Postgres. This skill frames the real decision — migrate to
Prisma Next (the encouraged path), or stay on v6 where a hard blocker applies — and carries
the migration mechanics.
**Never do either of these:**
- Never advise a MongoDB project to "upgrade to Prisma 7". The connector does not exist
there. The `prisma-upgrade-v7` guide does not apply to MongoDB projects.
- Never solve the version question by rewriting the app onto a SQL database. Changing the
database engine is a separate, much larger decision that is not yours to make implicitly.
## The version landscape
| Version | MongoDB status |
|---------|----------------|
| Prisma ORM v6 | Fully supported (`mongodb` provider); latest 6.x is the current stable path; maintenance line |
| Prisma ORM v7 | **No MongoDB connector — not an option, ever** |
| Prisma Next | MongoDB support in **Early Access**, actively developed, GA planned after Postgres — the successor path for MongoDB projects |
## The decision, up front
**Migrating to Prisma Next is the encouraged path.** MongoDB support in Prisma Next is Early
Access: functional and moving quickly, with GA planned after Postgres — and the Prisma team
wants MongoDB users to migrate early and share feedback. The migration mechanics are
detailed in the references.
**Staying on the latest v6 remains a legitimate choice where a hard blocker applies** —
stated plainly: the Next Mongo façade does not wrap transactions yet (the underlying driver
is available directly; this is expected to change soon), and pre-1.0 minors can carry
breaking changes with published upgrade recipes.
### Decision table
| Signal | Direction |
|--------|-----------|
| No blockers below apply | Migrate to Next; run the `verify-cutover-checklist` and share feedback with the Prisma team |
| Greenfield / prototype / internal tool | Migrate to Next |
| Codebase uses multi-document transactions (`$transaction`) — check with grep, do not ask | Plan raw-driver session equivalents first (see `client-api-mapping`), or stay on v6 until the façade wrapper lands |
| Team cannot absorb pre-1.0 breaking upgrades between minors | Stay on v6 until GA |
| Risk-averse but interested | Run a staged Next round-trip on a copy (see `verify-cutover-checklist`), then migrate |
Note: the transactions gap is expected to close soon — this section will be updated when
façade transactions merge in Prisma Next.
### If staying on v6: hygiene (a deliberate stay, not neglect)
- Pin the Prisma packages to the latest 6.x line and keep taking 6.x patch releases.
- Track Prisma release notes and security advisories for the 6.x line.
- Keep the classic v6 MongoDB setup: `url = env("DATABASE_URL")` in the schema, `db push`
workflow, no SQL driver adapters (see `prisma-database-setup` for the v6 MongoDB shape).
- Re-evaluate when Prisma Next's MongoDB is GA, or when blockers for trying EA are resolved.
## Reference files
| Reference | What it covers |
|-----------|----------------|
| `references/decision-stay-or-migrate.md` | The full decision framing, blocker checks, and stay-hygiene detail |
| `references/schema-contract-mapping.md` | v6 schema (`mongodb` provider, `@db.ObjectId`, composite types) → Next contract concepts |
| `references/client-api-mapping.md` | v6 client calls → Next equivalents, incl. raw escape hatches and transactions — names map, parity does not |
| `references/migrations-mapping.md` | v6 `db push`-only story → Next's plan/migrate/verify/sign flow |
| `references/verify-cutover-checklist.md` | No-data-moves verification: same DB, index parity, staged round-trip before cutover |
## Verified against
Behavioral claims about Prisma Next in this skill were verified against
[prisma/prisma-next](https://github.com/prisma/prisma-next) at commit
`a2791c5dd59d579b4b3052942ae7f8fe5e2ee852` (pre-1.0, ~v0.14/0.15 line). Prisma Next moves
quickly in Early Access: **before acting on any Next-side claim, verify it against the
version actually installed** (check the project's `@prisma-next/*` versions and the
prisma-next skills installed with it). Next's Mongo target requires MongoDB 8.0+ and expects
`mongodb@^7` as a user-supplied peer dependency.
## Hand-off rule
This skill is the **discovery bridge**, not a replacement for Prisma Next's own
documentation. After a project switches to Prisma Next, run Prisma Next's `init`/skill
installation and follow its own skills (quickstart, contract, queries, migrations, runtime)
for day-to-day work — do not keep working from this skill's summaries.

View File

@ -0,0 +1,61 @@
# client-api-mapping
How v6 Prisma Client calls map to Prisma Next's Mongo client — names map, parity does not.
## Priority
CRITICAL
## Why It Matters
The v6 and Next client APIs look superficially similar, but none of the v6 MongoDB raw
methods exist under their old names, aggregation moved to a different lane entirely, and
transactions go through the driver rather than a façade wrapper. Assuming parity produces
code that does not compile — or, in the transactions case, code that silently loses
atomicity.
## The mapping
| v6 call | Prisma Next equivalent | Notes |
|---------|------------------------|-------|
| `prisma.user.findMany(...)` | `db.orm.users.where(...).all()` | Fluent ORM lane; storage-name keys (see `schema-contract-mapping.md`) |
| `prisma.user.findFirst(...)` | `db.orm.users.where(...).first()` | |
| `create` / `update` / `upsert` / `delete` / `updateMany` / `deleteMany` | `create` / `update` / `upsert` / `delete` / `updateAll` / `deleteAll` on `db.orm.<collection>` | See Prisma Next's `prisma-next-queries` skill |
| `prisma.user.aggregate(...)`, `groupBy(...)` | **No ORM equivalent.** Use the typed aggregation-pipeline builder: `db.query.from(...).match(...).group(...).build()` | Prisma Next's `prisma-next-queries` skill covers the builder lane |
| `$runCommandRaw(...)` ([v6 docs](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#runcommandraw)) | **Name does not exist in Next.** Raw lane is `mongoRaw(...)` → a raw collection with `aggregate`, `insertOne/Many`, `updateOne/Many`, `deleteOne/Many`, `findOneAndUpdate/Delete`. For arbitrary database commands, use the underlying `mongodb` driver directly — it is a user-supplied peer dependency and fully accessible | Check the installed version's raw surface |
| `<model>.findRaw(...)` ([v6 docs](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#findraw)) | `mongoRaw(...)` collection reads (e.g. `aggregate` with a `$match` stage) | No direct `findRaw` name |
| `<model>.aggregateRaw(...)` ([v6 docs](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#aggregateraw)) | `mongoRaw(...).aggregate(...)` or the typed pipeline builder | |
| `$transaction(...)` — works on v6 with a replica set ([v6 docs](https://www.prisma.io/docs/orm/overview/databases/mongodb#replica-set-configuration)) | The façade does not wrap `db.transaction(...)` yet, **but the underlying `mongodb` driver is directly available** (user-supplied peer dependency): multi-document atomicity works today via driver sessions (`client.startSession()` / `session.withTransaction(...)`) on a replica set | A façade wrapper is expected soon; this row will be updated when it merges |
| `$connect` / `$disconnect` | `connect()` / `close()` on the Mongo façade client | |
## Bad
```typescript
// Assuming v6 names exist in Prisma Next:
await db.user.$runCommandRaw({ collStats: 'users' }); // no such method
await db.transaction(async (tx) => { ... }); // no such method on the Mongo façade
```
## Good
```typescript
// Raw lane under its Next name:
const raw = mongoRaw(db);
await raw.users.aggregate([{ $match: { status: 'active' } }]);
// Aggregation through the typed pipeline builder:
const stats = await db.query.from('users').group({ _id: '$role', n: { $count: {} } }).build();
// Multi-document atomicity today: the mongodb driver (a direct dependency of the
// project) exposes sessions and transactions as usual:
const session = mongoClient.startSession();
await session.withTransaction(async () => {
// ...writes...
});
```
## References
- [v6 MongoDB raw queries](https://www.prisma.io/docs/orm/prisma-client/using-raw-sql/raw-queries#raw-queries-with-mongodb)
- [v6 replica set requirement for transactions](https://www.prisma.io/docs/orm/overview/databases/mongodb#replica-set-configuration)
- Prisma Next queries + runtime skills (`skills/prisma-next-queries`, incl. its dedicated `mongo.md`; `skills/prisma-next-runtime`) — authoritative for the Next side; verified @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852`

View File

@ -0,0 +1,87 @@
# decision-stay-or-migrate
How to decide between migrating a MongoDB project to Prisma Next and staying on Prisma v6.
## Priority
CRITICAL
## Why It Matters
MongoDB projects cannot follow the general "upgrade Prisma" advice: Prisma 7 has no MongoDB
connector, so the forward path is Prisma Next. Advising an impossible v7 upgrade, or
silently rewriting the app onto SQL, are both serious failure modes. The encouraged path is
migrating to Prisma Next — its MongoDB support is Early Access and the Prisma team wants
early adopters' feedback — with a deliberate stay on v6 where a hard blocker applies.
## The facts the decision rests on
Prisma Next side (verified against prisma/prisma-next @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852`;
status confirmed by the Prisma team 2026-07):
- **MongoDB support is Early Access**, actively developed, with GA planned after Postgres.
- The implementation is deep, not a stub: a full package family (ORM, typed
aggregation-pipeline builder, raw lane, driver over the official `mongodb` package),
first-class contract-driven migrations, and extensive tests against real in-memory MongoDB.
- **The Mongo client façade does not wrap `db.transaction(...)` yet** — multi-document
atomicity is done through the MongoDB driver's session API, which is directly available
(the `mongodb` package is a user-supplied peer dependency). A façade wrapper is expected;
this skill will be updated when it merges.
- Early Access means pre-1.0 minors can carry breaking changes, with published upgrade
recipes (e.g. 0.11→0.12 changed Mongo validator emission and made `mongodb` a
user-supplied peer dependency). Floor: MongoDB 8.0 and `mongodb@^7`.
Prisma v6 side:
- v6 fully supports MongoDB, including transactions on replica sets — "MongoDB only allows
you to start a transaction on a replica set. Prisma ORM uses transactions internally"
([replica set configuration](https://www.prisma.io/docs/orm/overview/databases/mongodb#replica-set-configuration)).
- v6 MongoDB has no Prisma Migrate; the workflow is `db push`
([no support for Prisma Migrate](https://www.prisma.io/docs/orm/overview/databases/mongodb#no-support-for-prisma-migrate)).
## Blocker checks before migrating
Run these checks yourself — from the codebase, not by asking the user:
- **Search the codebase for `$transaction` usage** (grep for `$transaction`). If present,
plan the raw-driver session equivalents before migrating (see `client-api-mapping.md`) —
or stay on v6 until the façade wrapper lands.
- **Check the MongoDB server version** (must be 8.0+ for Next; v6 tolerated older).
- **Confirm the team can absorb pre-1.0 upgrades.** Next publishes versioned upgrade recipes
between minors; someone has to run them. For a production app, confirm the user accepts
Early Access status before migrating.
## Bad
```text
User: "We're on Prisma 6 with MongoDB. Should we upgrade to Prisma 7?"
Agent: "Yes — here's the v7 upgrade guide. Step 1: install a driver adapter..."
```
Prisma 7 has no MongoDB connector; this migration is impossible and the SQL driver-adapter
steps corrupt a working v6 setup.
## Good
```text
User: "We're on Prisma 6 with MongoDB. Should we upgrade to Prisma 7?"
Agent: "Prisma 7 does not support MongoDB — v6 is the last classic-ORM
major for MongoDB. The path forward is Prisma Next, the successor: its MongoDB support is
Early Access and migrating is encouraged. Let me check the codebase for blockers first —
searching for $transaction usage and checking the MongoDB server version..."
```
## Stay-on-v6 hygiene
Staying is a decision, not a default-by-neglect:
- Pin `prisma` and `@prisma/client` to the latest 6.x and keep taking 6.x patches.
- Watch Prisma release notes and security advisories for the 6.x maintenance line.
- Keep the classic setup (`url = env("DATABASE_URL")` in the schema; `db push`; no SQL
driver adapters).
- Re-evaluate when Prisma Next's MongoDB is GA, or when blockers for trying EA are resolved.
## References
- [Prisma Next repository](https://github.com/prisma/prisma-next)
- [Prisma v6 MongoDB documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb)

View File

@ -0,0 +1,65 @@
# migrations-mapping
How the v6 MongoDB "no migrations" story maps onto Prisma Next's first-class migration flow.
## Priority
HIGH
## Why It Matters
This is the largest workflow change in the migration — in v6, MongoDB explicitly has no
Prisma Migrate, while in Prisma Next MongoDB participates in the full migration lifecycle.
Teams porting a `db push` habit into Next without understanding the plan/verify/sign flow
will fight the tooling or bypass its safety rails.
## v6: `db push` only
MongoDB on v6 has no Prisma Migrate and no plans to add it — "MongoDB projects do not rely
on internal schemas" ([no support for Prisma Migrate](https://www.prisma.io/docs/orm/overview/databases/mongodb#no-support-for-prisma-migrate)).
The workflow is `prisma db push` to sync indexes and unique constraints, with no migration
history on disk.
## Prisma Next: first-class, contract-driven migrations (Mongo included)
Migration authoring in Next is first-class for Postgres **and Mongo** (prisma-next
`skills/prisma-next-migrations/SKILL.md`) — MongoDB is not a push-only special case:
- **Flow:** contract *emit* → diff → *plan* (writes a content-hashed migration package) →
*migrate* (apply in graph order) → *verify* (live schema vs destination contract) →
*sign* (advance the marker after a verify pass).
- **Mongo migration ops** come from dedicated factories: `createCollection`,
`dropCollection`, `validatedCollection`, `setValidation`, `createIndex`, `dropIndex`,
`collMod`, and `dataTransform` for data backfills.
- **Marker storage:** Next records migration state in a document in the
`_prisma_migrations` collection (per space) — the same collection name family v6 users
know from SQL, repurposed for Mongo state.
- **DDL is not transactional on Mongo:** the runner applies operations, verifies the live
schema against the destination contract, and only advances the marker on a verify pass —
making interrupted runs resumable rather than atomic (see Prisma Next's
`prisma-next-migrations` skill).
- **Push-style alternative still exists:** `db update` diffs the live database against the
contract and applies directly without writing a migration directory — the closest
analogue to the v6 `db push` habit, at the cost of no history.
- Validators: Next emits closed `$jsonSchema` validators by default since 0.12 (prisma-next
`CHANGELOG.md`) — collections gain schema enforcement v6 never applied.
## Bad
```text
Porting the v6 habit: run the Next equivalent of `db push` for every change in production,
accumulating no migration history, and hand-editing collections when verification fails.
```
## Good
```text
Adopt the Next lifecycle: emit the contract, plan a migration package, apply it with
migrate, let verify gate the marker, and sign. Reserve `db update` for local prototyping,
mirroring how `db push` was used on v6.
```
## References
- [v6: no Prisma Migrate for MongoDB](https://www.prisma.io/docs/orm/overview/databases/mongodb#no-support-for-prisma-migrate)
- Prisma Next migrations skill (`skills/prisma-next-migrations`) — authoritative for the Next side; verified @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852`

View File

@ -0,0 +1,52 @@
# schema-contract-mapping
How v6 MongoDB schema concepts map onto Prisma Next's contract model.
## Priority
HIGH
## Why It Matters
Prisma Next does not consume the v6 `schema.prisma` as-is: the schema becomes a *contract*
(authored in PSL or TypeScript via the contract builder), and several v6 MongoDB idioms have
different — or deliberately absent — equivalents. Translating mechanically without knowing
the mapping produces contracts that fail verification or, worse, silently change collection
addressing.
## The mapping
| v6 concept | Prisma Next equivalent | Notes |
|------------|------------------------|-------|
| `datasource db { provider = "mongodb" }` + `url = env(...)` ([v6 docs](https://www.prisma.io/docs/orm/overview/databases/mongodb#example)) | `defineConfig` from `@prisma-next/mongo/config` wiring the mongo family/target/adapter/driver descriptors | Next selects MongoDB by importing the `@prisma-next/mongo` façade, not by a provider string in the schema; `prisma-next init` accepts `mongodb` as a target name |
| `@id @default(auto()) @map("_id") @db.ObjectId` ([using ObjectId](https://www.prisma.io/docs/orm/overview/databases/mongodb#using-objectid)) | ObjectId-typed id field in the Next contract (PSL or TS builder) | Verify the exact attribute surface against the installed Next version's `prisma-next-contract` skill — the contract builder also exposes `index` and `valueObject` |
| Composite (embedded) types — MongoDB-only in v6 ([composite types](https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/composite-types)) | Value objects / embedded shapes in the Next contract (`valueObject` in the Mongo contract builder) | Same conceptual role: documents embedded in a parent document |
| Model names address the client (`prisma.user`) | **Collection storage names** address the ORM: `db.orm.users`, i.e. the `@@map(...)` name or the lowercased model name — not `db.orm.User` | prisma-next `skills/prisma-next/SKILL.md`, `skills/prisma-next-quickstart/SKILL.md`; the most common porting mistake |
| Indexes declared in schema, applied by `db push` | Indexes are contract-declared and applied through migrations (`createIndex`/`dropIndex` factories) | See `migrations-mapping.md` |
| No native polymorphism | No schema-layer polymorphism on Mongo either: `@@base`/`@@discriminator` are SQL-only in Next; model an explicit `discriminator` field | prisma-next `skills/prisma-next-contract/SKILL.md` |
## Bad
```typescript
// Ported from v6 and addressed by model name:
const user = await db.orm.User.first(); // undefined — Mongo ORM keys are storage names
```
## Good
```typescript
// Mongo ORM keys are collection storage names (@@map or lowercased model name):
const user = await db.orm.users.first();
```
## Environment requirements
Prisma Next's Mongo target requires MongoDB 8.0+ and `mongodb@^7` installed by the user as a
peer dependency (prisma-next `CHANGELOG.md`, 0.11→0.12). v6 supports older MongoDB servers,
so check the server version before planning a migration.
## References
- [v6 MongoDB schema documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb)
- [v6 composite types (MongoDB-only)](https://www.prisma.io/docs/orm/prisma-client/special-fields-and-types/composite-types)
- Prisma Next contract skill (`skills/prisma-next-contract`) in the prisma-next repository — authoritative for the Next side

View File

@ -0,0 +1,60 @@
# verify-cutover-checklist
Verification checklist for a v6 → Prisma Next cutover: the data never moves — only the code does.
## Priority
CRITICAL
## Why It Matters
A v6 → Next migration is a *client and workflow* migration against the **same MongoDB
database** — there is no data export/import step, and introducing one (or pointing the new
stack at a fresh database) turns a code migration into an outage. The checklist below keeps
the cutover observable and reversible.
## Ground rules
- **No data moves.** The Next contract is authored to describe the existing collections;
both stacks read the same database during the staged phase.
- **v6 stays runnable until cutover is verified.** Do not delete the v6 client, schema, or
dependencies until the checklist passes.
## Checklist
1. **Same database, verified:** the Next config points at the same connection string /
database name the v6 app uses (minus v6-specific URL parameters that the `mongodb@^7`
driver rejects — validate the URL with the driver first).
2. **Server floor:** MongoDB server is 8.0+ (Next's requirement; v6 tolerated older).
Confirm before authoring any contract.
3. **Contract round-trip on a copy:** on a staging copy (or `mongodb-memory-server`), emit
the contract, run plan → migrate → verify → sign, and confirm `verify` passes against
data copied from production shape. Verification failures here are contract-mapping bugs,
not database problems.
4. **Index parity:** enumerate indexes on every collection (`db.collection.getIndexes()`)
and confirm the Next contract declares the same set — v6 `db push` may have created
indexes the new contract must re-declare, or verification and query performance will
diverge.
5. **Validator impact assessed:** Next emits closed `$jsonSchema` validators by default;
confirm legacy documents (extra fields, drifted shapes) pass them on the staging copy
before applying to production.
6. **Storage-name addressing audited:** every ported call site uses collection storage
names (`db.orm.users`), not model names (see `schema-contract-mapping.md`).
7. **Transaction inventory mapped:** grep the v6 app for `$transaction`; each hit gets a
driver-session equivalent (the `mongodb` driver is directly available; the façade wrapper
is expected soon — see `client-api-mapping.md`).
8. **Raw call inventory mapped:** every `$runCommandRaw` / `findRaw` / `aggregateRaw` call
has an explicit Next-side replacement (`mongoRaw(...)` lane or pipeline builder).
9. **Staged read-only soak:** run the Next stack read-only against staging/production data
alongside v6 and compare outputs before allowing writes.
10. **Cutover + rollback:** switch writes to Next only after the soak; keep the v6 branch
deployable as the rollback path. Rolling back is a code rollback — the data was never
moved.
After cutover, install and follow Prisma Next's own skills for ongoing work (see the
hand-off rule in `SKILL.md`).
## References
- [v6 MongoDB documentation](https://www.prisma.io/docs/orm/overview/databases/mongodb)
- Prisma Next migrations + queries skills — authoritative for the Next side; verified @ `a2791c5dd59d579b4b3052942ae7f8fe5e2ee852`

View File

@ -0,0 +1,263 @@
---
name: prisma-postgres-setup
description: Set up a new Prisma Postgres database and connect it to a local project using the Management API. Use when asked to "set up a database", "create a Prisma Postgres project", "get a connection string", "connect my app to Prisma Postgres", or "provision a database".
license: MIT
metadata:
author: prisma
version: "1.1.0"
---
# Prisma Postgres Setup
Procedural skill that guides you through provisioning a new Prisma Postgres database via the Management API and connecting it to a local project.
## When to Apply
Use this skill when:
- Setting up a new Prisma Postgres database for a project
- Creating a Prisma Postgres project and connecting it locally
- Obtaining a connection string for Prisma Postgres
- Provisioning a database via the Management API (not the Console UI)
Do **not** use this skill when:
- Setting up CI/CD preview databases — use `prisma-postgres-cicd`
- Building multi-tenant database provisioning into an app — use `prisma-postgres-integrator`
- Working with a database that already exists and is connected (schema/migration tasks are standard Prisma CLI)
## Prerequisites
- Node.js 18+
- A Prisma Postgres workspace (create one at https://console.prisma.io if needed)
- A workspace service token (see `references/auth.md`)
## UX Guidelines
When presenting choices to the user (region selection, project deletion, etc.), **use your platform's interactive selection mechanism** (e.g., `ask` tool in Claude Code, structured prompts in other agents). Do not print static tables and ask the user to type a value — present selectable options so the user can pick with minimal effort.
## Workflow
Follow these steps in order. Each step includes the API call to make and how to handle the response.
### Step 1: Authenticate
You need a service token. Try these methods in order:
**1a. Token in the user's prompt**
Check if the user included a service token in their initial message (e.g., "Set up Prisma Postgres with token eyJ..."). If so, use it **exactly as provided** — do not truncate, re-encode, or round-trip it through a file. Store it in a shell variable for subsequent calls.
**1b. Token in the environment**
Check for `PRISMA_SERVICE_TOKEN` in the environment or `.env` file.
**1c. Ask the user to create one**
If no token is available, instruct the user:
> Create a service token in Prisma Console → Workspace Settings → Service Tokens.
> Copy the token and paste it here.
Read `references/auth.md` for details on service token creation.
Once you have a token, store it in a shell variable (`PRISMA_SERVICE_TOKEN`) and use it for all subsequent API calls.
### Step 2: List available regions
Fetch the list of available Prisma Postgres regions to let the user choose where to deploy.
```bash
curl -s -H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
https://api.prisma.io/v1/regions/postgres
```
The response contains an array of regions with `id`, `name`, and `status`. Only present regions where `status` is `available`.
**Present the regions as an interactive menu** — let the user pick from options rather than typing a region ID manually.
Read `references/endpoints.md` for the full response shape.
### Step 3: Create a project with a database
```bash
curl -s -X POST https://api.prisma.io/v1/projects \
-H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "<project-name>",
"region": "<region-id>",
"createDatabase": true
}'
```
Use the current directory name as the project name by default.
The response is wrapped in `{ "data": { ... } }`. Extract:
- `data.id` — the project ID (prefixed with `proj_`)
- `data.database.id` — the database ID (prefixed with `db_`)
- `data.database.connections[0].endpoints.direct.connectionString` — the direct PostgreSQL connection string
Use the **direct** connection string (`endpoints.direct.connectionString`). Do not use the pooled or accelerate endpoints — those are for legacy Accelerate setups and not needed for new projects.
If the response status is `provisioning`, wait a few seconds and poll `GET /v1/databases/<database-id>` until `status` is `ready`.
**If creation fails due to a database limit**, list the user's existing projects and present them as an interactive menu for deletion. After the user picks one, delete it and retry.
Read `references/endpoints.md` for the full request/response shapes.
### Step 4: Create a named connection (optional)
If you need a dedicated connection (e.g., per-developer or per-environment), create one:
```bash
curl -s -X POST https://api.prisma.io/v1/databases/<database-id>/connections \
-H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
-H "Content-Type: application/json" \
-d '{ "name": "dev" }'
```
Extract the direct connection string from `data.endpoints.direct.connectionString`.
### Step 5: Configure the local project
1. Install dependencies:
```bash
npm install prisma @prisma/client @prisma/adapter-pg pg dotenv
```
All five packages are required:
- `prisma` — CLI for migrations, schema push, client generation
- `@prisma/client` — the generated query client
- `@prisma/adapter-pg` — Prisma 7 driver adapter for direct PostgreSQL connections
- `pg` — Node.js PostgreSQL driver (used by the adapter)
- `dotenv` — loads `.env` variables for `prisma.config.ts`
2. Write the direct connection string to `.env`. **Append** to the file if it already exists — do not overwrite existing entries:
```
DATABASE_URL="<direct-connection-string>"
```
3. Verify `.gitignore` includes `.env`. Create `.gitignore` if it does not exist. Warn the user if `.env` is not gitignored.
4. Ensure `package.json` has `"type": "module"` set (Prisma 7 generates ESM output).
5. If `prisma/schema.prisma` does not exist, run `npx prisma init` to scaffold the project. This creates both `prisma/schema.prisma` and `prisma.config.ts`.
6. Ensure `schema.prisma` has the `postgresql` provider and **no** `url` or `directUrl` in the datasource block (Prisma 7 manages connection URLs in `prisma.config.ts`, not in the schema):
```prisma
datasource db {
provider = "postgresql"
}
```
7. Ensure `prisma.config.ts` loads the connection URL from the environment:
```typescript
import path from 'node:path'
import { defineConfig } from 'prisma/config'
import 'dotenv/config'
export default defineConfig({
earlyAccess: true,
schema: path.join(import.meta.dirname, 'prisma', 'schema.prisma'),
datasource: {
url: process.env.DATABASE_URL!,
},
})
```
**Important Prisma 7 notes:**
- Connection URLs go in `prisma.config.ts`, never in `schema.prisma`
- The provider in `schema.prisma` must be `"postgresql"` (not `"prismaPostgres"`)
- `dotenv/config` must be imported in `prisma.config.ts` to load `.env` variables
### Step 6: Define schema and push
If the schema already has models, skip to pushing. Otherwise, **present these options as an interactive menu**:
1. **"I'll define my schema manually"** — Tell the user to edit `prisma/schema.prisma` and come back when ready. Wait for them before proceeding.
2. **"Give me a starter schema"** — Add a Blog starter schema (User, Post, Comment with relations) to `prisma/schema.prisma`. Show the user what was added and ask if they want to adjust it before pushing.
3. **"I'll describe what I need"** — Ask the user to describe their data model in natural language (e.g., "I'm building a task manager with projects, tasks, and team members"). Generate a schema from the description, show it, and ask for confirmation before pushing.
Once the schema has models and the user is ready, create a migration and generate the client:
```bash
npx prisma migrate dev --name init
```
This creates migration files in `prisma/migrations/` **and** generates the client in one step. Migration history is essential for CI/CD workflows (`prisma migrate deploy`) and production deployments.
Only use `npx prisma db push` if the user explicitly asks for prototyping-only mode (no migration history). In that case, follow it with `npx prisma generate`.
### Step 7: Verify the connection
After generating the client, create and run a quick verification script to confirm everything works end-to-end. This is **critical** — do not skip this step.
Create a file named `test-connection.ts`:
```typescript
import 'dotenv/config'
import pg from 'pg'
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from './generated/prisma/client.js'
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
const adapter = new PrismaPg(pool)
const prisma = new PrismaClient({ adapter })
const result = await prisma.$queryRawUnsafe('SELECT 1 as connected')
console.log('Connected to Prisma Postgres:', result)
await prisma.$disconnect()
await pool.end()
```
Run it:
```bash
npx tsx test-connection.ts
```
**Prisma 7 client instantiation rules:**
- Import from `./generated/prisma/client.js` (not `./generated/prisma`)
- Create a `pg.Pool` with the `DATABASE_URL` connection string
- Wrap it in a `PrismaPg` adapter
- Pass `{ adapter }` to the `PrismaClient` constructor
- Do **not** use `datasourceUrl` — that option does not exist in Prisma 7
- Do **not** use `new PrismaClient()` with no arguments — it will throw
After verification succeeds, delete `test-connection.ts`.
Then share links for the user to explore their database:
- **Prisma Studio (CLI):** `npx prisma studio` — opens a visual data browser locally
- **Console:** `https://console.prisma.io/<workspaceId>/<projectId>/<databaseId>/dashboard` — strip the prefixes (`wksp_`, `proj_`, `db_`) from the IDs returned in Step 3 to build this URL
Read `references/prisma7-client.md` for the full client instantiation reference.
## Error Handling
Read `references/api-basics.md` for the full error reference. Key self-correction patterns:
| HTTP Status | Error Code | Action |
|---|---|---|
| 401 | `authentication-failed` | Service token is invalid or expired. Ask the user to create a new one in Console → Workspace Settings → Service Tokens. |
| 404 | `resource-not-found` | Check that the resource ID includes the correct prefix (`proj_`, `db_`, `con_`). |
| 422 | `validation-error` | Check request body against the endpoint schema. Common: missing `name`, invalid `region`. |
| 429 | `rate-limit-exceeded` | Back off and retry after a few seconds. |
## Reference Files
Detailed API and usage information is in:
```
references/auth.md — Service token creation and usage
references/api-basics.md — Base URL, envelope, IDs, errors, pagination
references/endpoints.md — Endpoint details for projects, databases, connections, regions
references/prisma7-client.md — Prisma 7 client instantiation and usage patterns
```

View File

@ -0,0 +1,102 @@
# api-basics
Core conventions for the Prisma Management API. All three `prisma-postgres-*` skills share these patterns.
## Base URL
```
https://api.prisma.io/v1
```
API documentation: https://api.prisma.io/v1/doc
## Response Envelope
### Single resource
```json
{
"data": {
"id": "proj_clx7abc123def456",
"type": "project",
"name": "My Project",
"createdAt": "2025-06-15T10:30:00.000Z"
}
}
```
### Collection
```json
{
"data": [
{ "id": "proj_aaa", "type": "project", "name": "Alpha" },
{ "id": "proj_bbb", "type": "project", "name": "Beta" }
],
"pagination": {
"hasMore": true,
"nextCursor": "clx7cursor123"
}
}
```
## Resource ID Prefixes
Every resource ID carries a type prefix:
| Prefix | Resource |
|---|---|
| `proj_` | Project |
| `db_` | Database |
| `con_` | Connection |
| `wksp_` | Workspace |
Always include the prefix when sending IDs in API requests.
## Pagination
Collection endpoints use cursor-based pagination:
```
GET /v1/projects?limit=10
GET /v1/projects?cursor=clx7abc123&limit=10
```
| Parameter | Type | Default | Description |
|---|---|---|---|
| `cursor` | string | — | Opaque cursor from `nextCursor` |
| `limit` | number | 100 | Maximum items per page |
Continue fetching while `pagination.hasMore` is `true`, using `pagination.nextCursor` as the `cursor` parameter.
## Error Responses
All errors follow this shape:
```json
{
"error": {
"code": "resource-not-found",
"message": "database with id db_abc not found"
}
}
```
### Error codes by HTTP status
| HTTP Status | Error Code | Meaning |
|---|---|---|
| 400 | `client-error` | Malformed request |
| 401 | `authentication-failed` | Missing or invalid token |
| 403 | `permission-denied` | Token lacks required access |
| 404 | `resource-not-found` | Resource does not exist or is not accessible |
| 422 | `validation-error` | Request body failed validation |
| 429 | `rate-limit-exceeded` | Too many requests |
| 500 | `internal-server-error` | Server error — retry after a delay |
### Self-correction patterns
- **401**: Token is invalid or expired. Create a new service token in Console → Workspace Settings → Service Tokens.
- **404**: Verify the resource ID includes the correct prefix (`proj_`, `db_`, `con_`). Use `GET /v1/projects` or `GET /v1/databases` to list available resources.
- **422**: Check the request body against the endpoint schema. Common issues: missing required fields, invalid region ID, empty `name`.
- **429**: Wait 25 seconds and retry. If repeated, increase the backoff interval.

View File

@ -0,0 +1,46 @@
# auth
How to authenticate with the Prisma Management API using service tokens.
## Service Tokens
Service tokens authenticate server-to-server requests. They are scoped to a workspace and grant access to all resources within it.
### Creating a service token
1. Open https://console.prisma.io
2. Navigate to **Workspace Settings** → **Service Tokens**
3. Click **Create Token**
4. Copy the token immediately — it is only shown once
### Using a service token
Set the token as an environment variable:
```bash
export PRISMA_SERVICE_TOKEN="eyJ..."
```
Include it in the `Authorization` header of every API request:
```bash
curl -H "Authorization: Bearer $PRISMA_SERVICE_TOKEN" \
https://api.prisma.io/v1/projects
```
### Token scope
Service tokens are workspace-scoped. A single token grants access to all projects, databases, and connections within the workspace. There are no project-scoped tokens at this time.
### Security practices
- Store tokens in environment variables or secret managers, never in source code
- Add `.env` to `.gitignore` to prevent accidental commits
- Rotate tokens periodically via Console → Workspace Settings → Service Tokens
- In CI/CD, store tokens as encrypted secrets (e.g., GitHub Secrets)
## OAuth 2.0 (for user-scoped access)
OAuth is used when acting on behalf of a user, typically in partner/integrator flows. See the `prisma-postgres-integrator` skill for OAuth details.
For standard database setup, service tokens are the recommended authentication method.

View File

@ -0,0 +1,223 @@
# endpoints
Management API endpoint details for database setup workflows.
## List regions
```
GET /v1/regions/postgres
```
No request body. Returns available Prisma Postgres regions.
**Response:**
```json
{
"data": [
{
"id": "us-east-1",
"type": "region",
"name": "US East (N. Virginia)",
"status": "available"
},
{
"id": "eu-west-1",
"type": "region",
"name": "EU West (Ireland)",
"status": "available"
}
]
}
```
Only use regions where `status` is `available`.
## Create project (with database)
```
POST /v1/projects
```
**Request body:**
```json
{
"name": "my-project",
"region": "us-east-1",
"createDatabase": true
}
```
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
| `name` | string | No | Auto-generated | Project display name |
| `region` | string | No | `us-east-1` | Region for the database |
| `createDatabase` | boolean | No | `true` | Create a default database with the project |
**Response** (with `createDatabase: true`):
```json
{
"data": {
"id": "proj_clx7abc123",
"type": "project",
"url": "https://api.prisma.io/v1/projects/proj_clx7abc123",
"name": "my-project",
"createdAt": "2025-06-15T10:30:00.000Z",
"defaultRegion": "us-east-1",
"workspace": {
"id": "wksp_xyz789",
"url": "https://api.prisma.io/v1/workspaces/wksp_xyz789",
"name": "My Workspace"
},
"database": {
"id": "db_def456",
"type": "database",
"url": "https://api.prisma.io/v1/databases/db_def456",
"name": "my-project",
"status": "ready",
"createdAt": "2025-06-15T10:30:00.000Z",
"isDefault": true,
"defaultConnectionId": "con_ghi789",
"connections": [
{
"id": "con_ghi789",
"type": "connection",
"url": "https://api.prisma.io/v1/connections/con_ghi789",
"name": "Default",
"createdAt": "2025-06-15T10:30:00.000Z",
"kind": "postgres",
"endpoints": {
"direct": {
"host": "db.prisma.io",
"port": 5432,
"connectionString": "postgres://user:pass@db.prisma.io:5432/postgres?sslmode=require"
}
}
}
],
"region": {
"id": "us-east-1",
"name": "US East (N. Virginia)"
}
}
}
}
```
Key field to extract:
- `data.database.connections[0].endpoints.direct.connectionString` → use as `DATABASE_URL`
The response also includes `pooled` and `accelerate` endpoints — ignore these for new projects. The direct connection string is all you need.
If `data.database.status` is `provisioning`, poll `GET /v1/databases/{id}` until `status` is `ready`.
## Get database
```
GET /v1/databases/{databaseId}
```
Use to check database status after creation or to retrieve database details.
**Response:**
```json
{
"data": {
"id": "db_def456",
"type": "database",
"url": "https://api.prisma.io/v1/databases/db_def456",
"name": "my-project",
"status": "ready",
"createdAt": "2025-06-15T10:30:00.000Z",
"isDefault": true,
"defaultConnectionId": "con_ghi789",
"connections": [],
"project": {
"id": "proj_clx7abc123",
"url": "https://api.prisma.io/v1/projects/proj_clx7abc123",
"name": "my-project"
},
"region": {
"id": "us-east-1",
"name": "US East (N. Virginia)"
}
}
}
```
## Create connection
```
POST /v1/databases/{databaseId}/connections
```
Creates a new named connection string for a database. Use for per-developer or per-environment connections.
**Request body:**
```json
{
"name": "dev"
}
```
| Field | Type | Required | Description |
|---|---|---|---|
| `name` | string | Yes | Display name for the connection |
**Response:**
```json
{
"data": {
"id": "con_newcon123",
"type": "connection",
"url": "https://api.prisma.io/v1/connections/con_newcon123",
"name": "dev",
"createdAt": "2025-06-15T10:31:00.000Z",
"kind": "postgres",
"endpoints": {
"direct": {
"host": "db.prisma.io",
"port": 5432,
"connectionString": "postgres://user:pass@db.prisma.io:5432/postgres?sslmode=require"
}
},
"database": {
"id": "db_def456",
"url": "https://api.prisma.io/v1/databases/db_def456",
"name": "my-project"
}
}
}
```
Extract: `data.endpoints.direct.connectionString` → use as `DATABASE_URL`.
## Delete database
```
DELETE /v1/databases/{databaseId}
```
Permanently deletes a database and all its connections. Returns `204 No Content` on success.
## List projects
```
GET /v1/projects
```
Returns all projects in the workspace. Supports cursor-based pagination (`?cursor=...&limit=...`).
## Delete project
```
DELETE /v1/projects/{projectId}
```
Permanently deletes a project and all its databases. Returns `204 No Content` on success.

View File

@ -0,0 +1,82 @@
# Prisma 7 Client Instantiation
Prisma 7 changed how PrismaClient connects to databases. The CLI (`prisma db push`, `prisma migrate`) reads the URL from `prisma.config.ts`. But at **runtime**, you must provide a driver adapter to PrismaClient explicitly.
## Required packages
```bash
npm install @prisma/client @prisma/adapter-pg pg
```
- `@prisma/adapter-pg` — the Prisma adapter for the `pg` PostgreSQL driver
- `pg` — the underlying Node.js PostgreSQL driver
## Basic instantiation
```typescript
import 'dotenv/config'
import pg from 'pg'
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from './generated/prisma/client.js'
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
const adapter = new PrismaPg(pool)
const prisma = new PrismaClient({ adapter })
```
## Key rules
1. **Import path**: Always `./generated/prisma/client.js` — not `./generated/prisma` and not `@prisma/client`.
2. **Adapter is mandatory**: `new PrismaClient()` with no arguments throws. `new PrismaClient({ datasourceUrl: '...' })` also throws — `datasourceUrl` does not exist in Prisma 7.
3. **ESM required**: The generated client uses ESM. Ensure `package.json` has `"type": "module"`.
4. **Pool lifecycle**: Call `await pool.end()` when shutting down (after `prisma.$disconnect()`).
## Usage in application code
```typescript
import 'dotenv/config'
import pg from 'pg'
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from './generated/prisma/client.js'
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL })
const adapter = new PrismaPg(pool)
const prisma = new PrismaClient({ adapter })
// Create
const user = await prisma.user.create({
data: { email: 'alice@example.com', name: 'Alice' },
})
// Read with relations
const posts = await prisma.post.findMany({
where: { published: true },
include: { author: true },
})
// Update
await prisma.post.update({
where: { id: 1 },
data: { published: true },
})
// Delete
await prisma.post.delete({ where: { id: 1 } })
// Cleanup
await prisma.$disconnect()
await pool.end()
```
## Common mistakes
| Mistake | Error | Fix |
|---|---|---|
| `import { PrismaClient } from './generated/prisma'` | `Cannot find module` | Use `./generated/prisma/client.js` |
| `new PrismaClient()` | `PrismaClient needs non-empty options` | Pass `{ adapter }` |
| `new PrismaClient({ datasourceUrl: url })` | `Unknown property datasourceUrl` | Use adapter pattern instead |
| Missing `"type": "module"` in package.json | ESM import errors | Add `"type": "module"` |
| `import { PrismaClient } from '@prisma/client'` | Wrong export | Use `./generated/prisma/client.js` |

View File

@ -0,0 +1,145 @@
---
name: prisma-postgres
description: Prisma Postgres setup and operations guidance across Console, create-db CLI, Management API, and Management API SDK. Use when creating Prisma Postgres databases, working in Prisma Console, provisioning with create-db/create-pg/create-postgres, or integrating programmatic provisioning with service tokens or OAuth.
license: MIT
metadata:
author: prisma
version: "7.9.1"
---
# Prisma Postgres
Guidance for creating, managing, and integrating Prisma Postgres across interactive and programmatic workflows.
## When to Apply
Reference this skill when:
- Setting up Prisma Postgres from Prisma Console
- Provisioning instant temporary databases with `create-db`
- Linking an existing local project with `prisma postgres link`
- Managing Prisma Postgres resources via Management API
- Using `@prisma/management-api-sdk` in TypeScript/JavaScript
- Handling claim URLs, connection strings, regions, and auth flows
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | CLI Provisioning | CRITICAL | `create-db-cli` |
| 2 | Management API | CRITICAL | `management-api` |
| 3 | Management API SDK | HIGH | `management-api-sdk` |
| 4 | Console and Connections | HIGH | `console-and-connections` |
## Quick Reference
- `create-db-cli` - instant databases and current CLI flags (`--ttl`, `--copy`, `--quiet`, `--open`)
- `management-api` - service token and OAuth API workflows
- `management-api-sdk` - typed SDK usage with token storage
- `console-and-connections` - Console operations, `prisma postgres link`, direct TCP connections, and serverless-driver choices
## Core Workflows
### 1. Console-first workflow
Use Prisma Console for manual setup and operations:
- Open `https://console.prisma.io`
- Create/select workspace and project
- Use Studio in the project sidebar to view/edit data
- Retrieve direct connection details from the project UI
### 2. Quick provisioning with create-db
Use `create-db` when you need a database immediately:
```bash
npx create-db@latest
```
Aliases:
```bash
npx create-pg@latest
npx create-postgres@latest
```
For app integrations, you can also use the programmatic API (`create()` / `regions()`) from the `create-db` npm package.
Temporary databases auto-delete after ~24 hours unless claimed.
### 2b. Persistent databases with the Platform CLI
For databases that belong to a Project (not throwaway `create-db` databases), use `@prisma/cli`:
```bash
npx -y @prisma/cli@latest database create --help
npx -y @prisma/cli@latest database list --json
npx -y @prisma/cli@latest database connection create db_123
npx -y @prisma/cli@latest database usage db_123
npx -y @prisma/cli@latest database backup list db_123
```
`database create` and `database connection create` print a one-time connection URL; store it immediately. Destructive commands (`remove`, `restore`) require exact `--confirm <id>`.
For automation, prefer `--json --no-interactive`, resolve ids before mutations, and verify the installed command's help because this CLI is beta.
### 3. Link an existing local project
Use `prisma postgres link` when the database already exists and you want to wire a local project to it:
```bash
prisma postgres link
```
For CI or other non-interactive environments:
```bash
prisma postgres link --api-key "<your-api-key>" --database "db_..."
```
This flow updates your local `.env` with `DATABASE_URL`, then you can run `prisma generate` and `prisma migrate dev`.
### 4. Programmatic provisioning with Management API
Use API endpoints on:
```text
https://api.prisma.io/v1
```
Explore the schema and endpoints using:
- OpenAPI docs: `https://api.prisma.io/v1/doc`
- Swagger Editor: `https://api.prisma.io/v1/swagger-editor`
Auth options:
- Service token (workspace server-to-server)
- OAuth 2.0 (act on behalf of users)
### 5. Type-safe integration with Management API SDK
Install and use:
```bash
npm install @prisma/management-api-sdk
```
Use `createManagementApiClient` for existing tokens, or `createManagementApiSdk` for OAuth + token refresh.
The SDK exposes typed workspace service-token list, create, and revoke routes. A newly created token value is returned exactly once. Let the installed SDK types or OpenAPI document settle exact beta endpoint shapes.
## Rule Files
Detailed guidance lives in:
```
references/console-and-connections.md
references/create-db-cli.md
references/management-api.md
references/management-api-sdk.md
```
## How to Use
Start with `references/create-db-cli.md` for fast setup, then switch to `references/management-api.md` or `references/management-api-sdk.md` when you need programmatic provisioning.

View File

@ -0,0 +1,69 @@
# console-and-connections
Use Prisma Console workflows for project visibility, data inspection, and connection setup.
## Priority
HIGH
## Why It Matters
Many Prisma Postgres tasks are quickest in the Console: viewing Studio data, checking metrics, and retrieving connection details. This avoids unnecessary API or CLI work for simple operational tasks.
## Console workflow
1. Open `https://console.prisma.io`.
2. Select workspace and project.
3. Use dashboard metrics for usage and billing visibility.
4. Open the **Studio** tab in the sidebar to inspect and edit data.
## Local Studio
You can also inspect data locally:
```bash
npx prisma studio
```
## Linking an existing project
If the Prisma Postgres database already exists, link the local project instead of provisioning a new one:
```bash
prisma postgres link
```
For CI or non-interactive usage:
```bash
prisma postgres link --api-key "<your-api-key>" --database "db_..."
```
This command updates or creates `.env` with `DATABASE_URL`. If the project is already linked, use `--force` to re-link. After linking, run `prisma generate`, then `prisma migrate dev` if you need to apply the schema.
## Connection setup
For direct PostgreSQL tools and drivers:
- Generate/copy direct connection credentials from the project connection UI.
- Use the resulting PostgreSQL URL as `DATABASE_URL` for `pg` and `@prisma/adapter-pg`.
- For Prisma Postgres direct TCP, include `sslmode=require`.
Typical direct TCP format:
```env
DATABASE_URL="postgres://identifier:key@db.prisma.io:5432/postgres?sslmode=require"
```
Management API connection responses expose both `endpoints.direct` (`db.prisma.io:5432`) and `endpoints.pooled` (`pooled.db.prisma.io:5432`); prefer those fields over the deprecated flat `connectionString`. Connection secrets are shown once at creation (one-time view); store them immediately.
## Adapter choices
- Standard Node.js apps: prefer `@prisma/adapter-pg` with the direct TCP URL above.
- Edge/serverless runtimes: use `@prisma/adapter-ppg` with `@prisma/ppg` only when you specifically need the Prisma Postgres serverless driver.
## References
- [Prisma Postgres overview](https://www.prisma.io/docs/postgres/introduction/overview)
- [Viewing data](https://www.prisma.io/docs/postgres/integrations/viewing-data)
- [Direct connections](https://www.prisma.io/docs/postgres/database/direct-connections)

View File

@ -0,0 +1,136 @@
# create-db-cli
Use `create-db` for instant Prisma Postgres provisioning from the terminal.
## Priority
CRITICAL
## Why It Matters
`create-db` is the fastest way to get a working Prisma Postgres instance for development, demos, and CI previews. It can also emit machine-readable output and write env variables directly.
## Commands
```bash
npx create-db@latest
npx create-db@latest create [options]
npx create-db@latest regions
```
Aliases:
```bash
npx create-pg@latest
npx create-postgres@latest
```
## Command discovery (`--help`)
Always use `--help` first when integrating CLI commands:
```bash
npx create-db@latest --help
npx create-db@latest create --help
npx create-db@latest regions --help
```
Top-level commands currently exposed:
- `create` (default) to provision a database
- `regions` to list available regions
## `create` options
| Flag | Shorthand | Description |
|---|---|---|
| `--region [string]` | `-r` | Region choice: `ap-southeast-1`, `ap-northeast-1`, `eu-central-1`, `eu-west-3`, `us-east-1`, `us-west-1` |
| `--interactive [boolean]` | `-i` | Open region selector |
| `--json [boolean]` | `-j` | Output machine-readable JSON |
| `--env [string]` | `-e` | Write `DATABASE_URL` and `CLAIM_URL` into a target `.env` |
| `--ttl [string]` | `-t` | Auto-delete after a TTL like `30m` or `1h-24h` |
| `--copy [boolean]` | `-c` | Copy the connection string to the clipboard |
| `--quiet [boolean]` | `-q` | Only print the connection string |
| `--open [boolean]` | `-o` | Open the claim URL in your browser |
## Lifecycle and claim flow
- Databases are temporary by default.
- Unclaimed databases are auto-deleted after ~24 hours.
- Claim the database using the URL shown in command output to keep it permanently.
## Programmatic usage (library API)
You can also use `create-db` programmatically in Node.js/Bun instead of shelling out to the CLI.
Install:
```bash
npm install create-db
# or
bun add create-db
```
Create a database:
```ts
import { create, isDatabaseSuccess, isDatabaseError } from "create-db";
const result = await create({
region: "us-east-1",
userAgent: "my-app/1.0.0",
});
if (isDatabaseSuccess(result)) {
console.log(result.connectionString);
console.log(result.claimUrl);
console.log(result.deletionDate);
}
if (isDatabaseError(result)) {
console.error(result.error, result.message);
}
```
List regions programmatically:
```ts
import { regions } from "create-db";
const available = await regions();
console.log(available);
```
Programmatic `create()` defaults to `us-east-1` if no region is passed.
## Common patterns
```bash
# quick database
npx create-db@latest
# region-specific database
npx create-db@latest --region eu-central-1
# interactive region selection
npx create-db@latest --interactive
# write env vars for app bootstrap
npx create-db@latest --env .env
# auto-delete sooner
npx create-db@latest --ttl 2h
# copy connection string to clipboard
npx create-db@latest --copy
# print only the connection string
npx create-db@latest --quiet
# CI-friendly output
npx create-db@latest --json
```
## References
- [npx create-db docs](https://www.prisma.io/docs/postgres/introduction/npx-create-db)

View File

@ -0,0 +1,70 @@
# management-api-sdk
Use `@prisma/management-api-sdk` for typed API integration with optional OAuth and token refresh.
The Platform API evolves independently from Prisma ORM. Inspect the installed package's generated `api.d.ts` for exact paths and request/response shapes.
## Priority
HIGH
## Why It Matters
The SDK provides typed endpoint methods and removes boilerplate around auth and refresh handling, which reduces errors in production provisioning flows.
## Install
```bash
npm install @prisma/management-api-sdk
```
## Simple client (existing token)
```typescript
import { createManagementApiClient } from '@prisma/management-api-sdk'
const client = createManagementApiClient({ token: process.env.PRISMA_SERVICE_TOKEN! })
const { data: workspaces } = await client.GET('/v1/workspaces')
```
Check the generated client result before using `data`; typed clients surface HTTP failures separately. Never log a full response from connection/key creation because it may contain one-time credentials.
## Workspace service tokens
The typed client exposes routes to list, create, and revoke workspace service tokens:
- `GET /v1/workspaces/{workspaceId}/service-tokens`
- `POST /v1/workspaces/{workspaceId}/service-tokens`
- `DELETE /v1/workspaces/{workspaceId}/service-tokens/{serviceTokenId}`
Creation accepts a display `name`. The response's `data.value` is the complete token and is returned exactly once; transfer it directly to the intended secret store without logging the response. Later list calls return metadata and `valueHint`, not the token value. Treat revocation as destructive and resolve both ids explicitly.
## Full SDK (OAuth + refresh)
```typescript
import { createManagementApiSdk, type TokenStorage } from '@prisma/management-api-sdk'
const tokenStorage: TokenStorage = {
async getTokens() { return null },
async setTokens(tokens) {},
async clearTokens() {},
}
const api = createManagementApiSdk({
clientId: process.env.PRISMA_CLIENT_ID!,
redirectUri: 'https://your-app.com/auth/callback',
tokenStorage,
})
```
## OAuth SDK flow
1. Call `getLoginUrl()` and persist `state` + `verifier`.
2. Redirect user to login URL.
3. Handle callback with `handleCallback()`.
4. Use `api.client` for typed endpoint calls.
5. Call `logout()` when needed.
## References
- [Management API SDK docs](https://www.prisma.io/docs/postgres/introduction/management-api-sdk)

View File

@ -0,0 +1,79 @@
# management-api
Use Prisma Management API for programmatic provisioning and workspace/project/database management.
## Priority
CRITICAL
## Why It Matters
When you need backend automation, multi-tenant onboarding flows, or controlled resource provisioning, the Management API is the source of truth and is more reliable than interactive workflows.
## Base URL
```text
https://api.prisma.io/v1
```
## API exploration
- OpenAPI docs: `https://api.prisma.io/v1/doc`
- Swagger Editor: `https://api.prisma.io/v1/swagger-editor`
## Authentication methods
- Service token: best for server-to-server operations in your own workspace
- OAuth 2.0: best for acting on behalf of users across workspaces
## Service token flow
1. Create token in Prisma Console workspace settings.
2. Send token as Bearer auth:
```text
Authorization: Bearer $TOKEN
```
## OAuth flow summary
1. Redirect user to `https://auth.prisma.io/authorize` with `client_id`, `redirect_uri`, `response_type=code`, and scopes.
2. Receive `code` on callback.
3. Exchange code at `https://auth.prisma.io/token`.
4. Use returned access token in Management API requests.
## Resource model
Workspace -> Project -> Branch -> Database. Branches are a first-class resource: databases attach to a Branch, and branch-scoped env/databases are how preview isolation works.
## Current resource inventory
The 1.55 OpenAPI surface includes:
- workspaces, subscriptions, workspace integrations, workspace service tokens, and current-user metadata
- projects, transfers, project databases, and project/branch environment variables
- branches under a project plus branch get/update/delete operations
- databases, usage, backups, restore, connections, and connection rotation
- apps, deployments, promotion/rollback, runtime logs, domains, and build logs
- buckets and bucket keys
- source repositories, SCM installations/install intents, and repositories
- integrations and regions
App/deployment, branch mutation, SCM, and bucket routes include experimental surfaces. Read the installed SDK types or live OpenAPI before building durable automation around them.
Connection create/rotate responses reveal credentials once. Later reads redact or omit the secret, so store the URL immediately. Use the structured direct/pooled endpoint returned by the concrete operation; do not assume a historical flat response shape.
Workspace service-token creation also returns the complete token value exactly once. List calls expose only metadata and a `valueHint`; delete revokes the token. Keep workspace and token ids opaque, and never log a create response.
Database create supports explicit project, region, branch, and source context. A source may be empty, a backup, or another database. Backup records are incremental; rely on current fields and documented units rather than old full-backup examples.
## Notes
- Management API mutation responses may include direct connection credentials; treat the entire response as secret until redacted.
- Prefer an API-provided connection string over manually assembling one from fields.
## References
- [Management API docs](https://www.prisma.io/docs/postgres/introduction/management-api)
- [OpenAPI docs](https://api.prisma.io/v1/doc)
- [Swagger Editor](https://api.prisma.io/v1/swagger-editor)

View File

@ -0,0 +1,259 @@
---
name: prisma-upgrade-v7
description: Complete migration guide from Prisma ORM v6 to v7 covering all breaking changes. Use when upgrading Prisma versions, encountering v7 errors, or migrating existing projects. Triggers on "upgrade to prisma 7", "prisma 7 migration", "prisma-client generator", "driver adapter required".
license: MIT
metadata:
author: prisma
version: "7.6.0"
---
# Upgrade to Prisma ORM 7
Complete guide for migrating from Prisma ORM v6 to v7. This upgrade introduces significant breaking changes around the new `prisma-client` generator, driver adapters, `prisma.config.ts`, explicit environment loading, and generated client entrypoints.
## When to Apply
Reference this skill when:
- Upgrading from Prisma v6 to v7
- Updating to the `prisma-client` generator
- Setting up driver adapters
- Configuring `prisma.config.ts`
- Fixing import errors after upgrade
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Schema Migration | CRITICAL | `schema-changes` |
| 2 | Database Connectivity | CRITICAL | `driver-adapters` |
| 3 | Module System | CRITICAL | `esm-support` |
| 4 | Config and Env | HIGH | `prisma-config`, `env-variables` |
| 5 | Removed Features | HIGH | `removed-features` |
| 6 | Accelerate | HIGH | `accelerate-users` |
## Quick Reference
- `schema-changes` - generator migration, required output paths, generated entrypoints, and `Prisma.validator` replacement
- `driver-adapters` - required adapter installation for SQL providers, pool differences, and Prisma Postgres adapter choices
- `esm-support` - ESM-first setup plus CommonJS fallback with `moduleFormat = "cjs"`
- `prisma-config` - creating and using `prisma.config.ts`
- `env-variables` - explicit environment loading
- `removed-features` - removed middleware, metrics, and legacy CLI behavior
- `accelerate-users` - migration notes for Accelerate users
## Using MongoDB? This guide does not apply
Prisma 7 has no MongoDB connector. Do not apply any step in this guide to a project with
`provider = "mongodb"` — see the `prisma-mongodb-upgrade` skill for the actual decision
(stay on v6 deliberately vs migrate to Prisma Next).
## Important Notes
- **MongoDB projects should stay on Prisma 6.x or migrate to Prisma Next** - do not migrate MongoDB apps to Prisma 7's SQL client path (see `prisma-mongodb-upgrade`)
- **Node.js 20.19.0+** required
- **TypeScript 5.4.0+** required
- **Latest stable Prisma ORM version**: `7.6.0`
## Upgrade Steps Overview
1. Update packages to v7
2. Choose your module format (`esm` by default, `cjs` if needed)
3. Update TypeScript configuration
4. Update the schema generator block
5. Create `prisma.config.ts`
6. Install and configure a driver adapter for SQL providers
7. Update Prisma Client imports
8. Update client instantiation
9. Replace deprecated helper patterns like `Prisma.validator`
10. Run `prisma generate` and test
## Quick Upgrade Commands
```bash
# Update packages
npm install @prisma/client@7
npm install -D prisma@7
# Install a driver adapter (PostgreSQL or Prisma Postgres via direct TCP)
npm install @prisma/adapter-pg pg
# Install dotenv for env loading
npm install dotenv
# Regenerate client
npx prisma generate
```
## Breaking Changes Summary
| Change | v6 | v7 |
|--------|----|----|
| Module format | Implicit / mixed | ESM-first, `moduleFormat = "cjs"` supported |
| Generator provider | `prisma-client-js` | `prisma-client` is the default, while `prisma-client-js` still exists for legacy setups |
| Output path | Auto (node_modules) | Required explicit |
| Driver adapters | Optional | Required for SQL providers |
| Config file | `.env` + schema | `prisma.config.ts` |
| Env loading | Automatic | Manual (dotenv) |
| Generated entrypoints | Single package export | `client`, `browser`, `models`, `enums` entrypoints |
| Type-safe query fragments | `Prisma.validator()` | TypeScript `satisfies` |
| Middleware | `$use()` | Client Extensions |
| Metrics | Preview feature | Removed |
## Rule Files
Detailed migration guides for each breaking change:
```
references/esm-support.md - ESM and CommonJS configuration
references/schema-changes.md - Generator, output, imports, and generated entrypoints
references/driver-adapters.md - Required driver adapter setup
references/prisma-config.md - New configuration file
references/env-variables.md - Environment variable loading
references/removed-features.md - Middleware, metrics, and CLI flags
references/accelerate-users.md - Special handling for Accelerate
```
## Step-by-Step Migration
### 1. Update package.json for ESM-first projects
```json
{
"type": "module"
}
```
If you need to stay on CommonJS, keep your app as CJS and set `moduleFormat = "cjs"` in the generator block instead of forcing ESM.
### 2. Update tsconfig.json
```json
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "bundler",
"target": "ES2023",
"strict": true,
"esModuleInterop": true
}
}
```
### 3. Update schema.prisma
```prisma
// Before (v6)
generator client {
provider = "prisma-client-js"
}
// After (v7)
generator client {
provider = "prisma-client"
output = "../generated/prisma"
// Optional if you need CommonJS:
// moduleFormat = "cjs"
}
```
### 4. Create prisma.config.ts
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
})
```
### 5. Install a driver adapter (SQL providers only)
```bash
# PostgreSQL
npm install @prisma/adapter-pg pg
# MySQL
npm install @prisma/adapter-mariadb mariadb
# SQLite
npm install @prisma/adapter-better-sqlite3 better-sqlite3
# Prisma Postgres in standard Node.js apps (recommended)
npm install @prisma/adapter-pg pg
# Prisma Postgres serverless driver (edge/serverless)
npm install @prisma/adapter-ppg @prisma/ppg
# Neon
npm install @prisma/adapter-neon
```
MongoDB does not have a SQL `@prisma/adapter-*` package in the published Prisma 7.6.0 packages. If you're upgrading a MongoDB project, stop and keep that project on the latest Prisma 6.x release instead of following the standard Prisma 7 migration path.
### 6. Update client instantiation
```typescript
// Before (v6)
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// After (v7)
import { PrismaClient } from '../generated/prisma/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
### 7. Replace Prisma.validator with satisfies
```typescript
import { Prisma } from '../generated/prisma/client'
const userSelect = {
id: true,
email: true,
name: true,
} satisfies Prisma.UserSelect
```
### 8. Run migrations and generate
```bash
npx prisma generate
npx prisma migrate dev # if needed
```
## Troubleshooting
### "Cannot find module" errors
- Check that the generator `output` path matches your import path
- Ensure `prisma generate` ran successfully
### SSL certificate errors
- Add `ssl: { rejectUnauthorized: false }` to the adapter config if you need to preserve old behavior
- Or configure your certificates properly with `NODE_EXTRA_CA_CERTS` / OpenSSL CA settings
### Connection timeout issues
- Driver adapters use the underlying driver's defaults, which differ from v6
- Configure pool settings explicitly on the adapter if needed
## Resources
- [Official v7 Upgrade Guide](https://www.prisma.io/docs/orm/more/upgrades/to-v7)
- [Driver Adapters Documentation](https://www.prisma.io/docs/orm/core-concepts/supported-databases/database-drivers)
- [Prisma Config Reference](https://www.prisma.io/docs/orm/reference/prisma-config-reference)
## How to Use
Follow `references/schema-changes.md` and `references/driver-adapters.md` first, then apply the remaining reference files based on your project setup.

View File

@ -0,0 +1,151 @@
# Prisma Accelerate Users
Special migration instructions for users of Prisma Accelerate or Prisma Postgres with `prisma://` or `prisma+postgres://` URLs.
## Important
**Do NOT pass Accelerate URLs to driver adapters.**
Driver adapters (like `PrismaPg`) expect direct database connection strings. They will fail with `prisma://` or `prisma+postgres://` URLs.
## Correct v7 Setup for Accelerate
### 1. Keep your Accelerate URL
```env
# .env
DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=..."
# or
DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/..."
```
### 2. Install Accelerate extension
```bash
npm install @prisma/extension-accelerate
```
### 3. Configure 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'), // Accelerate URL works here
},
})
```
### 4. Instantiate client with accelerateUrl
```typescript
import { PrismaClient } from '../generated/client'
import { withAccelerate } from '@prisma/extension-accelerate'
// Use accelerateUrl instead of adapter
export const prisma = new PrismaClient({
accelerateUrl: process.env.DATABASE_URL,
}).$extends(withAccelerate())
```
## What NOT to Do
```typescript
// ❌ WRONG - Don't use adapter with Accelerate URL
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL // This will fail with prisma://
})
```
## Migrations with Accelerate
For migrations, you may need a direct database connection:
### Option 1: Use Accelerate URL for everything
Accelerate URLs work with Prisma CLI commands:
```bash
# Works with Accelerate URL
prisma migrate deploy
prisma db push
```
### Option 2: Use direct URL for migrations
```env
DATABASE_URL="prisma+postgres://..." # For app
DIRECT_DATABASE_URL="postgresql://..." # For migrations
```
```typescript
// prisma.config.ts
export default defineConfig({
datasource: {
url: env('DIRECT_DATABASE_URL'), // Direct URL for CLI
},
})
```
## Prisma Postgres (Cloud)
If using Prisma Postgres cloud database:
### Same approach
```typescript
import { PrismaClient } from '../generated/client'
import { withAccelerate } from '@prisma/extension-accelerate'
export const prisma = new PrismaClient({
accelerateUrl: process.env.DATABASE_URL, // prisma+postgres:// URL
}).$extends(withAccelerate())
```
## Switching Away from Accelerate
If you later switch to direct TCP connection:
```typescript
// Change from accelerateUrl to adapter
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL // Direct postgres:// URL
})
export const prisma = new PrismaClient({ adapter })
```
## Caching with Accelerate
The extension enables caching:
```typescript
const users = await prisma.user.findMany({
cacheStrategy: {
ttl: 60, // Cache for 60 seconds
swr: 120, // Stale-while-revalidate for 120 seconds
},
})
```
## Edge Runtime
Accelerate works great in edge runtimes:
```typescript
// Works in Vercel Edge, Cloudflare Workers, etc.
import { PrismaClient } from '../generated/client'
import { withAccelerate } from '@prisma/extension-accelerate'
export const prisma = new PrismaClient({
accelerateUrl: process.env.DATABASE_URL,
}).$extends(withAccelerate())
```

View File

@ -0,0 +1,267 @@
# Driver Adapters
Prisma v7 requires driver adapters for SQL database connections. This is the standard SQL execution path in current Prisma releases.
MongoDB should not follow this path. There is no published MongoDB `@prisma/adapter-*` package, and MongoDB projects should remain on the latest Prisma 6.x release instead of trying to fit into the Prisma 7 SQL adapter model.
## Why Driver Adapters?
- No native engine binary in the Prisma Client SQL path
- Smaller bundle size
- Better serverless/edge compatibility
- Uses native Node.js database drivers
- More control over connection pooling
## Available Adapters
| Database | Adapter Package | Underlying Driver |
|----------|-----------------|-------------------|
| PostgreSQL | `@prisma/adapter-pg` | `pg` |
| MySQL / MariaDB | `@prisma/adapter-mariadb` | `mariadb` |
| SQLite | `@prisma/adapter-better-sqlite3` | `better-sqlite3` |
| Prisma Postgres (Node.js) | `@prisma/adapter-pg` | `pg` |
| Prisma Postgres (edge/serverless) | `@prisma/adapter-ppg` | `@prisma/ppg` |
| SQL Server | `@prisma/adapter-mssql` | `mssql` |
| Neon | `@prisma/adapter-neon` | `@neondatabase/serverless` |
| PlanetScale | `@prisma/adapter-planetscale` | `@planetscale/database` |
| Turso/libSQL | `@prisma/adapter-libsql` | `@libsql/client` |
| D1 (Cloudflare) | `@prisma/adapter-d1` | Cloudflare D1 |
## Installation
### PostgreSQL
```bash
npm install @prisma/adapter-pg
```
### MySQL
```bash
npm install @prisma/adapter-mariadb mariadb
```
### SQLite
```bash
npm install @prisma/adapter-better-sqlite3
```
### Prisma Postgres
```bash
npm install @prisma/adapter-pg pg
```
### SQL Server
```bash
npm install @prisma/adapter-mssql mssql
```
## Configuration
### PostgreSQL
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
### MySQL
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaMariaDb } from '@prisma/adapter-mariadb'
const adapter = new PrismaMariaDb({
host: 'localhost',
port: 3306,
connectionLimit: 5,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE,
})
const prisma = new PrismaClient({ adapter })
```
### SQLite
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaBetterSqlite3 } from '@prisma/adapter-better-sqlite3'
const adapter = new PrismaBetterSqlite3({
url: process.env.DATABASE_URL || 'file:./dev.db'
})
const prisma = new PrismaClient({ adapter })
```
### Neon (Serverless PostgreSQL)
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaNeon } from '@prisma/adapter-neon'
const adapter = new PrismaNeon({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
### Prisma Postgres
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
})
const prisma = new PrismaClient({ adapter })
```
### Prisma Postgres serverless driver
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPostgresAdapter } from '@prisma/adapter-ppg'
const prisma = new PrismaClient({
adapter: new PrismaPostgresAdapter({
connectionString: process.env.PRISMA_DIRECT_TCP_URL,
}),
})
```
### SQL Server
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaMssql } from '@prisma/adapter-mssql'
const adapter = new PrismaMssql({
server: 'localhost',
port: 1433,
database: 'mydb',
user: process.env.SQLSERVER_USER,
password: process.env.SQLSERVER_PASSWORD,
options: {
encrypt: true,
trustServerCertificate: true,
},
})
const prisma = new PrismaClient({ adapter })
```
## Connection Pool Configuration
Driver adapters use the underlying driver's pool settings, which differ from v6 defaults.
### PostgreSQL with custom pool
```typescript
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
// Pool configuration
max: 10, // Maximum connections
idleTimeoutMillis: 30000, // Close idle connections after 30s
connectionTimeoutMillis: 5000, // Connection timeout (v6 default was 5s)
})
```
### Matching v6 behavior
```typescript
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
connectionTimeoutMillis: 5000, // v6 used 5 second timeout
})
```
## SSL Configuration
### Accept self-signed certificates
```typescript
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false // Accept self-signed certs
}
})
```
### Proper SSL configuration
```typescript
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL,
ssl: {
ca: fs.readFileSync('/path/to/ca-cert.pem'),
rejectUnauthorized: true
}
})
```
## Migration from v6
### Before (v6)
```typescript
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient({
datasources: {
db: { url: process.env.DATABASE_URL }
}
})
```
### After (v7)
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
## Singleton Pattern
```typescript
// lib/prisma.ts
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL!
})
export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter })
if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma
}
```

View File

@ -0,0 +1,161 @@
# Environment Variables
Prisma v7 no longer automatically loads environment variables. You must load them explicitly.
## The Change
### v6 Behavior
Prisma CLI automatically loaded `.env` files.
### v7 Behavior
You must manually load environment variables using `dotenv` or similar.
## Setup
### 1. Install dotenv
```bash
npm install dotenv
```
### 2. Import in prisma.config.ts
```typescript
import 'dotenv/config' // Must be first import
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Bun Users
Bun automatically loads `.env` files. No additional setup needed:
```typescript
// prisma.config.ts (Bun)
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Multiple .env Files
### Using dotenv-cli
```bash
npm install -D dotenv-cli
```
```json
{
"scripts": {
"db:migrate": "dotenv -e .env.local -- prisma migrate dev",
"db:push": "dotenv -e .env.development -- prisma db push"
}
}
```
### Using dotenv with path
```typescript
// prisma.config.ts
import { config } from 'dotenv'
import path from 'path'
// Load specific .env file
config({ path: path.join(__dirname, '.env.local') })
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Application Code
For your application, load env vars at startup:
### Entry point
```typescript
// index.ts
import 'dotenv/config'
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL!
})
const prisma = new PrismaClient({ adapter })
```
### Or use dotenv explicitly
```typescript
import { config } from 'dotenv'
config()
// Now process.env.DATABASE_URL is available
```
## Removed Environment Variables
These Prisma-specific env vars are removed in v7:
| Removed Variable | Alternative |
|-----------------|-------------|
| `PRISMA_CLI_QUERY_ENGINE_TYPE` | Not needed (no engines) |
| `PRISMA_CLIENT_ENGINE_TYPE` | Not needed (no engines) |
| `PRISMA_QUERY_ENGINE_BINARY` | Not needed |
| `PRISMA_QUERY_ENGINE_LIBRARY` | Not needed |
| `PRISMA_GENERATE_SKIP_AUTOINSTALL` | Not needed |
| `PRISMA_SKIP_POSTINSTALL_GENERATE` | Not needed |
| `PRISMA_GENERATE_IN_POSTINSTALL` | Not needed |
| `PRISMA_GENERATE_DATAPROXY` | Migrate to `prisma-client` with driver adapters |
| `PRISMA_GENERATE_NO_ENGINE` | Migrate to `prisma-client` with driver adapters |
| `PRISMA_CLIENT_NO_RETRY` | Configure on adapter |
| `PRISMA_MIGRATE_SKIP_GENERATE` | Not needed (auto-generate removed) |
| `PRISMA_MIGRATE_SKIP_SEED` | Not needed (auto-seed removed) |
## TypeScript env() Helper
The `env()` function from `prisma/config` provides type safety:
```typescript
import { env } from 'prisma/config'
// Type-safe environment variable access
const url = env('DATABASE_URL') // string
```
Note: This only works within `prisma.config.ts`, not in your application code.
## CI/CD Considerations
Ensure environment variables are set in your CI environment:
```yaml
# GitHub Actions
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
steps:
- run: npx prisma migrate deploy
```
No need for dotenv in CI if variables are set directly.

View File

@ -0,0 +1,128 @@
# ESM and CommonJS Support
Prisma ORM v7 is ESM-first, but the `prisma-client` generator can target either ESM or CommonJS. Use ESM by default, and opt into CommonJS with `moduleFormat = "cjs"` if your project still needs it.
## ESM Projects
Add `"type": "module"` to `package.json` and use an ESM-compatible `tsconfig.json`:
```json
{
"type": "module",
"scripts": {
"build": "tsc",
"start": "node dist/index.js"
}
}
```
```json
{
"compilerOptions": {
"module": "ESNext",
"moduleResolution": "bundler",
"target": "ES2023",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "dist"
},
"include": ["src/**/*", "prisma/**/*"]
}
```
## CommonJS Projects
If the rest of your app is still CommonJS, keep that setup and make the generated Prisma Client CommonJS too:
```json
{
"compilerOptions": {
"module": "CommonJS",
"moduleResolution": "node",
"target": "ES2022",
"esModuleInterop": true
}
}
```
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
moduleFormat = "cjs"
}
```
## Generator Fields That Matter
- `moduleFormat`: `esm` or `cjs`
- `runtime`: `nodejs`, `bun`, `deno`, `workerd`, `vercel-edge`, `react-native`
- `generatedFileExtension`: `ts`, `mts`, or `cts`
- `importFileExtension`: `ts`, `mts`, `cts`, `js`, `mjs`, `cjs`, or empty
Example:
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
runtime = "nodejs"
moduleFormat = "esm"
generatedFileExtension = "ts"
importFileExtension = "ts"
}
```
## Import Paths
### Server Code
```typescript
import { PrismaClient } from '../generated/prisma/client'
```
### Browser-Safe Types
```typescript
import { Prisma } from '../generated/prisma/browser'
import { Role } from '../generated/prisma/enums'
import type { UserModel } from '../generated/prisma/models/User'
```
## File Extensions
With `moduleResolution: "Node16"` or `"NodeNext"`, use `.js`/`.mjs`/`.cjs` extensions that match your emitted files.
With `moduleResolution: "bundler"`, bare relative imports are usually fine.
## Minimum Versions
| Requirement | Minimum Version |
|-------------|-----------------|
| Node.js | 20.19.0 |
| TypeScript | 5.4.0 |
## Framework Considerations
### Next.js
Next.js works well with the default ESM output. If you need generated types in client components, import them from `browser`, `models`, or `enums`, not from `client`.
### Bun
Bun loads `.env` files automatically, so ESM plus `env()` is the smoothest default. You can still choose `moduleFormat = "cjs"` if the rest of your project requires it.
## Troubleshooting
### "ERR_REQUIRE_ESM"
Your generated client is ESM, but your app is requiring it as CommonJS. Either switch the project to ESM or set `moduleFormat = "cjs"` and regenerate.
### "Cannot use import statement outside a module"
Your app is still being executed as CommonJS. Add `"type": "module"` or use `moduleFormat = "cjs"` instead.
### TypeScript compilation errors
Ensure `module`, `moduleResolution`, and your generator's `moduleFormat` agree with one another.

View File

@ -0,0 +1,203 @@
# Prisma Config
Prisma v7 introduces `prisma.config.ts` as the central configuration file for the Prisma CLI.
## Location
Place `prisma.config.ts` at your project root (next to `package.json`).
## Basic Configuration
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
})
```
## Configuration Options
### schema
Path to your Prisma schema file:
```typescript
schema: 'prisma/schema.prisma'
```
### datasource.url
Database connection URL:
```typescript
datasource: {
url: env('DATABASE_URL'),
}
```
### datasource.directUrl
Direct connection URL (bypassing connection pooler):
```typescript
datasource: {
url: env('DATABASE_URL'),
directUrl: env('DIRECT_DATABASE_URL'),
}
```
### datasource.shadowDatabaseUrl
Shadow database for migrations:
```typescript
datasource: {
url: env('DATABASE_URL'),
shadowDatabaseUrl: env('SHADOW_DATABASE_URL'),
}
```
### migrations.path
Directory for migration files:
```typescript
migrations: {
path: 'prisma/migrations',
}
```
### migrations.seed
Seed command for `prisma db seed`:
```typescript
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts',
}
```
## Full Example
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
export default defineConfig({
// Schema location
schema: 'prisma/schema.prisma',
// Migration configuration
migrations: {
path: 'prisma/migrations',
seed: 'tsx prisma/seed.ts',
},
// Database connection
datasource: {
url: env('DATABASE_URL'),
directUrl: env('DIRECT_DATABASE_URL'),
shadowDatabaseUrl: env('SHADOW_DATABASE_URL'),
},
})
```
## Environment Variables
### The env() helper
Use `env()` to reference environment variables:
```typescript
import { env } from 'prisma/config'
datasource: {
url: env('DATABASE_URL'),
}
```
This provides type safety but does NOT load .env files automatically.
### Loading .env files
Install and import dotenv:
```bash
npm install dotenv
```
```typescript
import 'dotenv/config' // Must be first import
import { defineConfig, env } from 'prisma/config'
```
## Migrating from v6
### Before (v6) - schema.prisma
```prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}
```
### After (v7) - 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'),
directUrl: env('DIRECT_URL'),
},
})
```
And update schema.prisma:
```prisma
datasource db {
provider = "postgresql"
// URLs now in prisma.config.ts
}
```
## Custom Config Path
Use `--config` flag with CLI commands:
```bash
prisma migrate dev --config ./config/prisma.config.ts
```
## Monorepo Configuration
```typescript
import 'dotenv/config'
import { defineConfig, env } from 'prisma/config'
import path from 'path'
export default defineConfig({
schema: path.join(__dirname, 'packages/database/prisma/schema.prisma'),
migrations: {
path: path.join(__dirname, 'packages/database/prisma/migrations'),
},
datasource: {
url: env('DATABASE_URL'),
},
})
```

View File

@ -0,0 +1,230 @@
# Removed Features
Several features have been removed in Prisma v7. Here's how to migrate.
## Client Middleware
### Removed
```typescript
// ❌ No longer works in v7
prisma.$use(async (params, next) => {
const before = Date.now()
const result = await next(params)
const after = Date.now()
console.log(`Query took ${after - before}ms`)
return result
})
```
### Use Client Extensions Instead
```typescript
// ✅ v7 approach
const prisma = new PrismaClient({ adapter }).$extends({
query: {
$allModels: {
async $allOperations({ operation, model, args, query }) {
const before = Date.now()
const result = await query(args)
const after = Date.now()
console.log(`${model}.${operation} took ${after - before}ms`)
return result
},
},
},
})
```
### Common Middleware Patterns
#### Soft delete
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
query: {
user: {
async delete({ args, query }) {
// Convert delete to soft delete
return prisma.user.update({
where: args.where,
data: { deletedAt: new Date() },
})
},
async findMany({ args, query }) {
// Filter out soft-deleted records
args.where = { ...args.where, deletedAt: null }
return query(args)
},
},
},
})
```
#### Logging
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
query: {
$allModels: {
async $allOperations({ operation, model, args, query }) {
console.log(`${model}.${operation}`, JSON.stringify(args))
return query(args)
},
},
},
})
```
## Metrics
### Removed
The Metrics preview feature has been removed.
```typescript
// ❌ No longer works
const metrics = await prisma.$metrics.json()
```
### Alternatives
#### Custom counter with extensions
```typescript
let totalQueries = 0
const prisma = new PrismaClient({ adapter }).$extends({
client: {
async $totalQueries() {
return totalQueries
},
},
query: {
$allModels: {
async $allOperations({ query, args }) {
totalQueries += 1
return query(args)
},
},
},
})
// Usage
const count = await prisma.$totalQueries()
```
#### Use driver-level metrics
Access metrics from the underlying driver adapter.
## CLI Flags Removed
### --skip-generate
Removed from `migrate dev` and `db push`.
```bash
# v6
prisma migrate dev --skip-generate
# v7 - generate is not run automatically
prisma migrate dev
prisma generate # Run explicitly if needed
```
Local verification with Prisma `7.6.0` showed no generated client files emitted by `migrate dev` or `db push`, even though some CLI help text still says `migrate dev` "trigger[s] generators".
### --skip-seed
Removed from `migrate dev`. More importantly, Prisma v7 no longer auto-runs seeds during `migrate dev` or `migrate reset`, so seed explicitly when you need it.
```bash
# v6
prisma migrate dev --skip-seed
# v7 - seed is not run automatically
prisma migrate dev
prisma db seed # Run explicitly if needed
```
### --schema and --url from db execute
```bash
# v6
prisma db execute --file ./script.sql --url "$DATABASE_URL"
# v7 - configure in prisma.config.ts
prisma db execute --file ./script.sql
```
## migrate diff Options
| Removed | Replacement |
|---------|-------------|
| `--from-url` | `--from-config-datasource` |
| `--to-url` | `--to-config-datasource` |
| `--from-schema-datasource` | `--from-config-datasource` |
| `--to-schema-datasource` | `--to-config-datasource` |
| `--shadow-database-url` | Configure in `prisma.config.ts` |
### Example
```bash
# v6
prisma migrate diff --from-url "$DATABASE_URL" --to-schema schema.prisma
# v7
prisma migrate diff --from-config-datasource --to-schema schema.prisma
```
## Automatic Behaviors Removed
### Auto-generate after migrate
```bash
# v7 workflow
prisma migrate dev --name add_field
prisma generate # Must run explicitly
```
### Auto-seed after migrate
```bash
# v7 workflow
prisma migrate reset --force
prisma db seed # Must run explicitly
```
## Prisma.validator
The `prisma-client` generator no longer exposes `Prisma.validator`. Use TypeScript's `satisfies` operator instead.
```typescript
import { Prisma } from '../generated/prisma/client'
const userSelect = {
id: true,
email: true,
} satisfies Prisma.UserSelect
```
## rejectOnNotFound
Removed in v5.0.0 (already deprecated).
```typescript
// ❌ Removed
const prisma = new PrismaClient({
rejectOnNotFound: true,
})
// ✅ Use OrThrow methods
const user = await prisma.user.findUniqueOrThrow({
where: { id: 1 },
})
const user = await prisma.user.findFirstOrThrow({
where: { email: 'test@example.com' },
})
```

View File

@ -0,0 +1,164 @@
# Schema Changes
Prisma v7 promotes `prisma-client` to the default generator. Update your generator block, output path, and imports accordingly.
This guide is for projects that are actually migrating to Prisma 7. Do not apply these schema changes to MongoDB projects; keep those on Prisma 6.x.
## Generator Block (v7)
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
```
## Key Changes
### 1. Provider name
Use `prisma-client` in Prisma v7. The older `prisma-client-js` generator still exists in the repo for legacy setups, but `prisma-client` is the default path for current projects.
### 2. Output is required
The `output` field is mandatory when using `prisma-client`. Prisma Client no longer generates to `node_modules` with this generator.
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
}
```
### 3. engineType changed
Legacy Rust engine settings are gone. With `prisma-client`, the relevant value is `engineType = "client"` if you want to state it explicitly, although it is typically inferred and can be omitted.
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
engineType = "client"
}
```
### 4. moduleFormat is explicit when needed
If you must stay on CommonJS:
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
moduleFormat = "cjs"
}
```
## Example Output Paths
### Standard project
```prisma
output = "../generated/prisma"
```
Creates files like:
```text
generated/prisma/
client.ts
browser.ts
enums.ts
models.ts
models/
```
### Monorepo
```prisma
output = "../../packages/database/generated/prisma"
```
### Same directory as schema
```prisma
output = "./generated/prisma"
```
Creates: `prisma/generated/prisma/client.ts`
## Datasource Block
The `url`, `directUrl`, and `shadowDatabaseUrl` fields in the `datasource` block are deprecated in Prisma v7. Move them to `prisma.config.ts` and keep only the provider in `schema.prisma`:
```prisma
datasource db {
provider = "postgresql"
}
```
```typescript
export default defineConfig({
datasource: {
url: env('DATABASE_URL'),
directUrl: env('DIRECT_URL'),
shadowDatabaseUrl: env('SHADOW_DATABASE_URL'),
},
})
```
## After Schema Changes
1. Run `prisma generate`:
```bash
npx prisma generate
```
2. Update imports throughout your codebase:
```typescript
import { PrismaClient } from '../generated/prisma/client'
```
3. Update `.gitignore` if you manage this manually:
```
/generated/prisma
```
4. Replace `Prisma.validator()` with TypeScript `satisfies` when using `prisma-client`:
```typescript
import { Prisma } from '../generated/prisma/client'
const userSelect = {
id: true,
email: true,
} satisfies Prisma.UserSelect
```
## Generated Entrypoints
- `client` - server-side Prisma Client and Prisma namespace
- `browser` - browser-safe types and enums without a real `PrismaClient`
- `enums` - slim enum-only entrypoint
- `models` - model types and derived helper types
## Preview Features
Preview features still work as before:
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
previewFeatures = ["relationJoins", "fullTextSearch"]
}
```
Recent preview-feature examples also include `partialIndexes` for PostgreSQL, SQLite, SQL Server, and CockroachDB:
```prisma
generator client {
provider = "prisma-client"
output = "../generated/prisma"
previewFeatures = ["partialIndexes"]
}
```

View File

@ -0,0 +1,265 @@
---
name: prisma-cli
description: Prisma ORM CLI commands reference covering init, generate, migrate, db, dev, complete, studio, validate, format, debug, and mcp. Use for ORM/database CLI workflows, not the Prisma Platform CLI. Triggers on "prisma init", "prisma generate", "prisma migrate", "prisma db", "prisma complete", "prisma studio", "prisma mcp".
license: MIT
metadata:
author: prisma
version: "7.9.1"
---
# 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: Platform and Compute
Do not confuse the stable ORM command (`prisma`) with the public-beta Platform package (`@prisma/cli`, binary `prisma-cli`). Use `prisma-compute` for Compute apps and workspace auth, and `prisma-postgres` for Platform projects and databases.
## 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`)
- Generating shell completions (`prisma complete`)
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Setup | HIGH | `init` |
| 2 | Generation | HIGH | `generate` |
| 3 | Development | HIGH | `dev` |
| 4 | Database | HIGH | `db-` |
| 5 | Migrations | CRITICAL | `migrate-` |
| 6 | Utility | MEDIUM | `complete`, `studio`, `validate`, `format`, `debug`, `mcp` |
## Command Categories
| Category | Commands | Purpose |
|----------|----------|---------|
| Setup | `init` | Initialize a 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 | `complete`, `studio`, `mcp`, `version`, `debug` | Shell, development, and AI tooling |
## 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 an example model
prisma init --with-model
```
### Client Generation
```bash
# 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):
```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
# 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
# Generate shell completion code
prisma complete zsh
```
## AI Safety Checkpoint
Prisma blocks destructive commands when it detects an AI agent until the agent has obtained explicit user consent. This covers `migrate reset`, `db push --force-reset`, and `db push --accept-data-loss`.
- Explain the exact data-loss impact and ask for consent immediately before running the command.
- Do not infer consent from earlier or unrelated messages.
- If automation needs the consent variable, set `PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION` to the user's exact consent message. Do not invent the text.
- The Prisma MCP server deliberately has no `migrate-reset` tool.
Read `references/agent-safety.md` before any destructive Prisma command.
## Current Prisma CLI Setup
### New Configuration File
Use `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'),
},
})
```
### 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`:
```typescript
// 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/complete.md - Shell completion generation
references/agent-safety.md - AI consent checkpoint for destructive commands
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.

View File

@ -0,0 +1,27 @@
# AI safety checkpoint for destructive commands
Prisma detects common AI-agent environments and blocks these commands until the user gives explicit consent:
- `prisma migrate reset`
- `prisma db push --force-reset`
- `prisma db push --accept-data-loss`
## Required workflow
1. Inspect the target database/config and explain exactly what can be deleted or reset.
2. Ask the user for explicit consent immediately before the action.
3. Run the command only after that consent.
For an agent-run subprocess, Prisma accepts the exact consent text through:
```bash
PRISMA_USER_CONSENT_FOR_DANGEROUS_AI_ACTION='<exact user consent message>' prisma migrate reset --force
```
The value must match the user's message exactly and must not contain added quotes or newlines. Never fabricate consent, reuse an old unrelated approval, or bypass the checkpoint by hiding agent-detection environment variables.
The MCP server has no `migrate-reset` tool. Use the shell command only after consent.
## Reference
- [Prisma ORM 7.9.0 release](https://github.com/prisma/prisma/releases/tag/7.9.0)

View File

@ -0,0 +1,22 @@
# prisma complete
Prints a shell completion script.
```bash
prisma complete zsh
prisma complete bash
prisma complete fish
prisma complete powershell
```
For a direct global CLI installation, load the output using the shell's normal startup mechanism. For example, in zsh:
```bash
source <(prisma complete zsh)
```
Prisma also integrates with supported package-manager completion flows. `npx` and `bunx` do not themselves provide completion; invoke the installed binary or the package manager's supported execution form such as `npm exec` or `bun x`.
## Reference
- [Prisma ORM 7.9.0 release](https://github.com/prisma/prisma/releases/tag/7.9.0)

View File

@ -0,0 +1,78 @@
# 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.

View File

@ -0,0 +1,185 @@
# 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

View File

@ -0,0 +1,150 @@
# 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 |
When Prisma detects an AI agent, `--force-reset` and `--accept-data-loss` require explicit user consent. Follow `agent-safety.md`; never infer or fabricate the consent text.
### 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.

View File

@ -0,0 +1,188 @@
# 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

View File

@ -0,0 +1,46 @@
# 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

View File

@ -0,0 +1,157 @@
# 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.

View File

@ -0,0 +1,48 @@
# 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

View File

@ -0,0 +1,173 @@
# 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'
```

View File

@ -0,0 +1,139 @@
# 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 | - |
| `--no-skills` | Skip the best-effort installation of Prisma agent skills | - |
`prisma init` attempts to install `prisma/skills` for detected agents. This is best-effort and does not make project initialization fail. Use `--no-skills` in minimal or controlled environments.
## 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

View File

@ -0,0 +1,39 @@
# 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 exposes `migrate-status`, `migrate-dev`, and Prisma Studio tooling. It does not expose the destructive `migrate-reset` tool; do not claim it is available or try to bypass that safety boundary.
- For destructive shell commands, follow `agent-safety.md` and obtain explicit user consent.
## References
- [Prisma CLI `mcp` command](https://docs.prisma.io/docs/cli/mcp)
- [Prisma MCP Server](https://www.prisma.io/docs/ai/tools/chatgpt)

View File

@ -0,0 +1,127 @@
# 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

View File

@ -0,0 +1,145 @@
# 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
Run `prisma generate` as an explicit follow-up when you need refreshed generated artifacts. Do not rely on historical CLI help that described generators as part of `migrate dev`.
## 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.

View File

@ -0,0 +1,89 @@
# 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.

View File

@ -0,0 +1,80 @@
# 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.**
When Prisma detects an AI agent, this command is blocked until the user gives explicit consent. Follow `agent-safety.md`; `--force` skips the ordinary prompt but does not constitute user consent for an agent.
## 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
```

View File

@ -0,0 +1,57 @@
# 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)

View File

@ -0,0 +1,65 @@
# 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.

View File

@ -0,0 +1,137 @@
# 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

View File

@ -0,0 +1,53 @@
# 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.)

View File

@ -0,0 +1,216 @@
---
name: prisma-client-api
description: Prisma Client API reference covering model queries, filters, operators, and client methods. Use when writing database queries, using CRUD operations, filtering data, or configuring Prisma Client. Triggers on "prisma query", "findMany", "create", "update", "delete", "$transaction".
license: MIT
metadata:
author: prisma
version: "7.9.1"
---
# Prisma Client API Reference
Complete API reference for Prisma Client. This skill provides guidance on model queries, filtering, relations, and client methods for current Prisma projects.
## When to Apply
Reference this skill when:
- Writing database queries with Prisma Client
- Performing CRUD operations (create, read, update, delete)
- Filtering and sorting data
- Working with relations
- Using transactions
- Configuring client options
## Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Client Construction | HIGH | `constructor` |
| 2 | Model Queries | CRITICAL | `model-queries` |
| 3 | Query Shape | HIGH | `query-options` |
| 4 | Filtering | HIGH | `filters` |
| 5 | Relations | HIGH | `relations` |
| 6 | Transactions | CRITICAL | `transactions` |
| 7 | Raw SQL | CRITICAL | `raw-queries` |
| 8 | Client Methods | MEDIUM | `client-methods` |
## Quick Reference
- `constructor` - `PrismaClient` setup, adapter wiring, logging, and SQL commenter plugins
- `model-queries` - CRUD operations and bulk operations
- `query-options` - `select`, `include`, `omit`, sort, pagination
- `filters` - scalar and logical filter operators
- `relations` - relation reads and nested writes
- `transactions` - array and interactive transaction patterns
- `raw-queries` - `$queryRaw` and `$executeRaw` safety
- `client-methods` - lifecycle methods, extensions, and `satisfies` patterns for `prisma-client`
## Client Instantiation
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
## Model Query Methods
| Method | Description |
|--------|-------------|
| `findUnique()` | Find one record by unique field |
| `findUniqueOrThrow()` | Find one or throw error |
| `findFirst()` | Find first matching record |
| `findFirstOrThrow()` | Find first or throw error |
| `findMany()` | Find multiple records |
| `create()` | Create a new record |
| `createMany()` | Create multiple records |
| `createManyAndReturn()` | Create multiple and return them |
| `update()` | Update one record |
| `updateMany()` | Update multiple records |
| `updateManyAndReturn()` | Update multiple and return them |
| `upsert()` | Update or create record |
| `delete()` | Delete one record |
| `deleteMany()` | Delete multiple records |
| `count()` | Count matching records |
| `aggregate()` | Aggregate values (sum, avg, etc.) |
| `groupBy()` | Group and aggregate |
## Query Options
| Option | Description |
|--------|-------------|
| `where` | Filter conditions |
| `select` | Fields to include |
| `include` | Relations to load |
| `omit` | Fields to exclude |
| `orderBy` | Sort order |
| `take` | Limit results |
| `skip` | Skip results (pagination) |
| `cursor` | Cursor-based pagination |
| `distinct` | Unique values only |
## Client Methods
| Method | Description |
|--------|-------------|
| `$connect()` | Explicitly connect to database |
| `$disconnect()` | Disconnect from database |
| `$transaction()` | Execute transaction |
| `$queryRaw()` | Execute raw SQL query |
| `$executeRaw()` | Execute raw SQL command |
| `$on()` | Subscribe to events |
| `$extends()` | Add extensions |
## Quick Examples
### Find records
```typescript
// Find by unique field
const user = await prisma.user.findUnique({
where: { email: 'alice@prisma.io' }
})
// Find with filter
const users = await prisma.user.findMany({
where: { role: 'ADMIN' },
orderBy: { createdAt: 'desc' },
take: 10
})
```
### Create records
```typescript
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
name: 'Alice',
posts: {
create: { title: 'Hello World' }
}
},
include: { posts: true }
})
```
### Update records
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: { name: 'Alice Smith' }
})
```
### Delete records
```typescript
await prisma.user.delete({
where: { id: 1 }
})
```
### Transactions
```typescript
const [user, post] = await prisma.$transaction([
prisma.user.create({ data: { email: 'alice@prisma.io' } }),
prisma.post.create({ data: { title: 'Hello', authorId: 1 } })
])
```
## Rule Files
Detailed API documentation:
```
references/constructor.md - PrismaClient constructor options
references/model-queries.md - CRUD operations
references/query-options.md - select, include, omit, where, orderBy
references/filters.md - Filter conditions and operators
references/relations.md - Relation queries and nested operations
references/transactions.md - Transaction API
references/raw-queries.md - $queryRaw, $executeRaw
references/client-methods.md - $connect, $disconnect, $on, $extends
```
## Filter Operators
| Operator | Description |
|----------|-------------|
| `equals` | Exact match |
| `not` | Not equal |
| `in` | In array |
| `notIn` | Not in array |
| `lt`, `lte` | Less than |
| `gt`, `gte` | Greater than |
| `contains` | String contains |
| `startsWith` | String starts with |
| `endsWith` | String ends with |
| `mode` | Case sensitivity |
## Relation Filters
| Operator | Description |
|----------|-------------|
| `some` | At least one related record matches |
| `every` | All related records match |
| `none` | No related records match |
| `is` | Related record matches (1-to-1) |
| `isNot` | Related record doesn't match |
## Resources
- [Prisma Client API Reference](https://www.prisma.io/docs/orm/reference/prisma-client-reference)
- [CRUD Operations](https://www.prisma.io/docs/orm/prisma-client/queries/crud)
- [Filtering and Sorting](https://www.prisma.io/docs/orm/prisma-client/queries/filtering-and-sorting)
## How to Use
Pick the category from the table above, then open the matching reference file for implementation details and examples.

View File

@ -0,0 +1,223 @@
# Client Methods
Prisma Client instance methods.
## $connect()
Explicitly connect to the database:
```typescript
const prisma = new PrismaClient({ adapter })
// Explicit connection
await prisma.$connect()
```
### When to use
Usually not needed - Prisma connects automatically on first query. Use for:
- Fail fast on startup
- Health checks
- Pre-warming connections
```typescript
async function main() {
try {
await prisma.$connect()
console.log('Database connected')
} catch (e) {
console.error('Failed to connect:', e)
process.exit(1)
}
}
```
## $disconnect()
Close database connection:
```typescript
await prisma.$disconnect()
```
### Graceful shutdown
```typescript
process.on('beforeExit', async () => {
await prisma.$disconnect()
})
// Or with SIGTERM
process.on('SIGTERM', async () => {
await prisma.$disconnect()
process.exit(0)
})
```
### In tests
```typescript
afterAll(async () => {
await prisma.$disconnect()
})
```
## $on()
Subscribe to events:
### Query events
```typescript
const prisma = new PrismaClient({
adapter,
log: [{ level: 'query', emit: 'event' }]
})
prisma.$on('query', (e) => {
console.log('Query:', e.query)
console.log('Params:', e.params)
console.log('Duration:', e.duration, 'ms')
})
```
### Log events
```typescript
const prisma = new PrismaClient({
adapter,
log: [
{ level: 'info', emit: 'event' },
{ level: 'warn', emit: 'event' },
{ level: 'error', emit: 'event' }
]
})
prisma.$on('info', (e) => console.log(e.message))
prisma.$on('warn', (e) => console.warn(e.message))
prisma.$on('error', (e) => console.error(e.message))
```
## $extends()
Add extensions for custom behavior:
### Add custom methods
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
client: {
$log: (message: string) => console.log(message)
}
})
prisma.$log('Hello!')
```
### Add model methods
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
model: {
user: {
async findByEmail(email: string) {
return prisma.user.findUnique({ where: { email } })
}
}
}
})
const user = await prisma.user.findByEmail('alice@prisma.io')
```
### Query extensions
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
query: {
user: {
async findMany({ args, query }) {
// Add default filter
args.where = { ...args.where, deletedAt: null }
return query(args)
}
}
}
})
```
### Result extensions
```typescript
const prisma = new PrismaClient({ adapter }).$extends({
result: {
user: {
fullName: {
needs: { firstName: true, lastName: true },
compute(user) {
return `${user.firstName} ${user.lastName}`
}
}
}
}
})
const user = await prisma.user.findFirst()
console.log(user.fullName) // Computed field
```
### Chain extensions
```typescript
const prisma = new PrismaClient({ adapter })
.$extends(loggingExtension)
.$extends(softDeleteExtension)
.$extends(computedFieldsExtension)
```
## $transaction()
See `transactions.md` for details.
## $queryRaw() / $executeRaw()
See `raw-queries.md` for details.
## Type utilities
### Prisma namespace
```typescript
import { Prisma } from '../generated/client'
// Input types
type UserCreateInput = Prisma.UserCreateInput
type UserWhereInput = Prisma.UserWhereInput
// Output types
type User = Prisma.UserGetPayload<{}>
type UserWithPosts = Prisma.UserGetPayload<{
include: { posts: true }
}>
```
### Type-safe query fragments with satisfies
Type-safe query fragments:
```typescript
import { Prisma } from '../generated/client'
const userSelect = {
id: true,
email: true,
name: true
} satisfies Prisma.UserSelect
const user = await prisma.user.findUnique({
where: { id: 1 },
select: userSelect
})
```
With the `prisma-client` generator, use TypeScript `satisfies` for typed query fragments. You may still see older examples that use `Prisma.validator()` with `prisma-client-js`.

View File

@ -0,0 +1,221 @@
# PrismaClient Constructor
Configure Prisma Client when instantiating.
## Basic Instantiation
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
## Constructor Options
### adapter (Required for the SQL provider workflow)
Driver adapter instance:
```typescript
import { PrismaPg } from '@prisma/adapter-pg'
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL
})
const prisma = new PrismaClient({ adapter })
```
### accelerateUrl (For Accelerate users)
```typescript
import { withAccelerate } from '@prisma/extension-accelerate'
const prisma = new PrismaClient({
accelerateUrl: process.env.DATABASE_URL, // prisma:// URL
}).$extends(withAccelerate())
```
### log
Configure logging:
```typescript
const prisma = new PrismaClient({
adapter,
log: ['query', 'info', 'warn', 'error'],
})
```
#### Log levels
| Level | Description |
|-------|-------------|
| `query` | All SQL queries |
| `info` | Informational messages |
| `warn` | Warnings |
| `error` | Errors |
#### Log to events
```typescript
const prisma = new PrismaClient({
adapter,
log: [
{ level: 'query', emit: 'event' },
{ level: 'error', emit: 'stdout' },
],
})
prisma.$on('query', (e) => {
console.log('Query:', e.query)
console.log('Duration:', e.duration, 'ms')
})
```
### errorFormat
Control error formatting:
```typescript
const prisma = new PrismaClient({
adapter,
errorFormat: 'pretty', // 'pretty' | 'colorless' | 'minimal'
})
```
### comments
Attach SQL commenter plugins for observability, tracing, or query insights:
```typescript
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
import { prismaQueryInsights } from '@prisma/sqlcommenter-query-insights'
import { queryTags, withQueryTags } from '@prisma/sqlcommenter-query-tags'
import { traceContext } from '@prisma/sqlcommenter-trace-context'
const prisma = new PrismaClient({
adapter: new PrismaPg(process.env.DATABASE_URL!),
comments: [prismaQueryInsights(), traceContext(), queryTags()],
})
await withQueryTags({ route: '/api/users', requestId: 'req-123' }, () =>
prisma.user.findMany(),
)
```
Use `comments` only for SQL providers. This is the clean way to add trace or query-shape metadata without changing your query calls.
### transactionOptions
Default transaction settings:
```typescript
const prisma = new PrismaClient({
adapter,
transactionOptions: {
maxWait: 5000, // Max wait to acquire transaction (ms)
timeout: 10000, // Max transaction duration (ms)
isolationLevel: 'Serializable',
},
})
```
### queryPlanCacheMaxSize
Use `queryPlanCacheMaxSize` to limit the in-memory query-plan cache:
```typescript
const prisma = new PrismaClient({
adapter,
queryPlanCacheMaxSize: 2_000,
})
```
The value must be a non-negative integer. Set it to `0` to disable query-plan caching; omit it to use Prisma's default. Treat this as a process-local memory/performance control, not a database prepared-statement setting.
## Singleton Pattern
Prevent multiple client instances in development:
```typescript
// lib/prisma.ts
import { PrismaClient } from '../generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}
function createPrismaClient() {
const adapter = new PrismaPg({
connectionString: process.env.DATABASE_URL!
})
return new PrismaClient({ adapter })
}
export const prisma = globalForPrisma.prisma ?? createPrismaClient()
if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma
}
```
## Next.js Pattern
```typescript
// lib/prisma.ts
import { PrismaClient } from '@/generated/client'
import { PrismaPg } from '@prisma/adapter-pg'
const createAdapter = () => new PrismaPg({
connectionString: process.env.DATABASE_URL!
})
const prismaClientSingleton = () => {
return new PrismaClient({ adapter: createAdapter() })
}
declare const globalThis: {
prismaGlobal: ReturnType<typeof prismaClientSingleton>
} & typeof global
const prisma = globalThis.prismaGlobal ?? prismaClientSingleton()
export default prisma
if (process.env.NODE_ENV !== 'production') {
globalThis.prismaGlobal = prisma
}
```
## Query Events
Listen to query events:
```typescript
const prisma = new PrismaClient({
adapter,
log: [{ level: 'query', emit: 'event' }],
})
prisma.$on('query', (e) => {
console.log('Query:', e.query)
console.log('Params:', e.params)
console.log('Duration:', e.duration)
})
```
## Log Events
```typescript
prisma.$on('info', (e) => console.log(e.message))
prisma.$on('warn', (e) => console.warn(e.message))
prisma.$on('error', (e) => console.error(e.message))
```

View File

@ -0,0 +1,256 @@
# Filter Conditions and Operators
Filter operators for the `where` clause.
## Equality
```typescript
// Exact match (implicit)
where: { email: 'alice@prisma.io' }
// Explicit equals
where: { email: { equals: 'alice@prisma.io' } }
// Not equal
where: { email: { not: 'alice@prisma.io' } }
```
## Comparison
```typescript
// Greater than
where: { age: { gt: 18 } }
// Greater than or equal
where: { age: { gte: 18 } }
// Less than
where: { age: { lt: 65 } }
// Less than or equal
where: { age: { lte: 65 } }
// Combined
where: { age: { gte: 18, lte: 65 } }
```
## Lists
```typescript
// In array
where: { role: { in: ['ADMIN', 'MODERATOR'] } }
// Not in array
where: { role: { notIn: ['GUEST', 'BANNED'] } }
```
## String Filters
```typescript
// Contains
where: { email: { contains: 'prisma' } }
// Starts with
where: { email: { startsWith: 'alice' } }
// Ends with
where: { email: { endsWith: '@prisma.io' } }
// Case-insensitive (default for some databases)
where: {
email: {
contains: 'PRISMA',
mode: 'insensitive'
}
}
```
## Null Checks
```typescript
// Is null
where: { deletedAt: null }
// Is not null
where: { deletedAt: { not: null } }
// Using isSet (for optional fields)
where: { middleName: { isSet: true } }
```
## Logical Operators
### AND (implicit)
```typescript
// Multiple conditions = AND
where: {
email: { contains: '@prisma.io' },
role: 'ADMIN'
}
```
### AND (explicit)
```typescript
where: {
AND: [
{ email: { contains: '@prisma.io' } },
{ role: 'ADMIN' }
]
}
```
### OR
```typescript
where: {
OR: [
{ email: { contains: '@gmail.com' } },
{ email: { contains: '@prisma.io' } }
]
}
```
### NOT
```typescript
where: {
NOT: {
role: 'GUEST'
}
}
// Multiple NOT conditions
where: {
NOT: [
{ role: 'GUEST' },
{ verified: false }
]
}
```
### Combined
```typescript
where: {
AND: [
{ verified: true },
{
OR: [
{ role: 'ADMIN' },
{ role: 'MODERATOR' }
]
}
],
NOT: { deletedAt: { not: null } }
}
```
## Relation Filters
### some
At least one related record matches:
```typescript
// Users with at least one published post
where: {
posts: {
some: { published: true }
}
}
```
### every
All related records match:
```typescript
// Users where all posts are published
where: {
posts: {
every: { published: true }
}
}
```
### none
No related records match:
```typescript
// Users with no published posts
where: {
posts: {
none: { published: true }
}
}
```
### is / isNot (1-to-1)
```typescript
// Users with profile in specific country
where: {
profile: {
is: { country: 'USA' }
}
}
// Users without profile
where: {
profile: {
isNot: null
}
}
```
## Array Field Filters
For fields like `String[]`:
```typescript
// Has element
where: { tags: { has: 'typescript' } }
// Has some elements
where: { tags: { hasSome: ['typescript', 'javascript'] } }
// Has every element
where: { tags: { hasEvery: ['typescript', 'prisma'] } }
// Is empty
where: { tags: { isEmpty: true } }
```
## JSON Filters
```typescript
// Path-based filter
where: {
metadata: {
path: ['settings', 'theme'],
equals: 'dark'
}
}
// String contains in JSON
where: {
metadata: {
path: ['bio'],
string_contains: 'developer'
}
}
```
## Full-Text Search
```typescript
// Requires @@fulltext index
where: {
content: {
search: 'prisma database'
}
}
```

View File

@ -0,0 +1,281 @@
# Model Queries
CRUD operations for your Prisma models.
## Read Operations
### findUnique
Find a single record by unique field:
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 }
})
const user = await prisma.user.findUnique({
where: { email: 'alice@prisma.io' }
})
```
#### With composite unique key
```typescript
// Model with @@unique([firstName, lastName])
const user = await prisma.user.findUnique({
where: {
firstName_lastName: {
firstName: 'Alice',
lastName: 'Smith'
}
}
})
```
### findUniqueOrThrow
Same as findUnique but throws if not found:
```typescript
const user = await prisma.user.findUniqueOrThrow({
where: { id: 1 }
})
// Throws PrismaClientKnownRequestError if not found
```
### findFirst
Find first matching record:
```typescript
const user = await prisma.user.findFirst({
where: { role: 'ADMIN' },
orderBy: { createdAt: 'desc' }
})
```
### findFirstOrThrow
```typescript
const user = await prisma.user.findFirstOrThrow({
where: { role: 'ADMIN' }
})
```
### findMany
Find multiple records:
```typescript
const users = await prisma.user.findMany({
where: { role: 'USER' },
orderBy: { name: 'asc' },
take: 10,
skip: 0
})
```
## Create Operations
### create
Create a single record:
```typescript
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
name: 'Alice'
}
})
```
#### With relations
```typescript
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
posts: {
create: [
{ title: 'First Post' },
{ title: 'Second Post' }
]
}
},
include: { posts: true }
})
```
### createMany
Create multiple records:
```typescript
const result = await prisma.user.createMany({
data: [
{ email: 'alice@prisma.io', name: 'Alice' },
{ email: 'bob@prisma.io', name: 'Bob' }
],
skipDuplicates: true // Skip records with duplicate unique fields
})
// Returns { count: 2 }
```
### createManyAndReturn
Create multiple and return them:
```typescript
const users = await prisma.user.createManyAndReturn({
data: [
{ email: 'alice@prisma.io', name: 'Alice' },
{ email: 'bob@prisma.io', name: 'Bob' }
]
})
// Returns array of created users
```
## Update Operations
### update
Update a single record:
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: { name: 'Alice Smith' }
})
```
#### Atomic operations
```typescript
const post = await prisma.post.update({
where: { id: 1 },
data: {
views: { increment: 1 },
likes: { decrement: 1 },
score: { multiply: 2 },
rating: { divide: 2 },
version: { set: 5 }
}
})
```
### updateMany
Update multiple records:
```typescript
const result = await prisma.user.updateMany({
where: { role: 'USER' },
data: { verified: true }
})
// Returns { count: 42 }
```
### updateManyAndReturn
```typescript
const users = await prisma.user.updateManyAndReturn({
where: { role: 'USER' },
data: { verified: true }
})
// Returns array of updated users
```
### upsert
Update or create:
```typescript
const user = await prisma.user.upsert({
where: { email: 'alice@prisma.io' },
update: { name: 'Alice Smith' },
create: { email: 'alice@prisma.io', name: 'Alice' }
})
```
## Delete Operations
### delete
Delete a single record:
```typescript
const user = await prisma.user.delete({
where: { id: 1 }
})
// Returns deleted record
```
### deleteMany
Delete multiple records:
```typescript
const result = await prisma.user.deleteMany({
where: { role: 'GUEST' }
})
// Returns { count: 5 }
// Delete all
const result = await prisma.user.deleteMany({})
```
## Aggregation Operations
### count
```typescript
const count = await prisma.user.count({
where: { role: 'ADMIN' }
})
```
### aggregate
```typescript
const result = await prisma.post.aggregate({
_avg: { views: true },
_sum: { views: true },
_min: { views: true },
_max: { views: true },
_count: { _all: true }
})
```
### groupBy
```typescript
const groups = await prisma.user.groupBy({
by: ['country'],
_count: { _all: true },
_avg: { age: true },
having: {
age: { _avg: { gt: 30 } }
}
})
```
## Return Types
| Method | Returns |
|--------|---------|
| `findUnique` | Record \| null |
| `findUniqueOrThrow` | Record (throws if not found) |
| `findFirst` | Record \| null |
| `findFirstOrThrow` | Record (throws if not found) |
| `findMany` | Record[] |
| `create` | Record |
| `createMany` | { count: number } |
| `createManyAndReturn` | Record[] |
| `update` | Record |
| `updateMany` | { count: number } |
| `delete` | Record |
| `deleteMany` | { count: number } |
| `count` | number |
| `aggregate` | Aggregate result |
| `groupBy` | Group result[] |

View File

@ -0,0 +1,276 @@
# Query Options
Options for controlling query behavior.
## select
Choose specific fields to return:
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
select: {
id: true,
name: true,
email: true,
// password: false (excluded by not including)
}
})
// Returns: { id: 1, name: 'Alice', email: 'alice@prisma.io' }
```
### Select relations
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
select: {
name: true,
posts: {
select: {
title: true,
published: true
}
}
}
})
```
### Select with include inside
```typescript
const user = await prisma.user.findMany({
select: {
name: true,
posts: {
include: {
comments: true
}
}
}
})
```
### Select relation count
```typescript
const users = await prisma.user.findMany({
select: {
name: true,
_count: {
select: { posts: true }
}
}
})
// Returns: { name: 'Alice', _count: { posts: 5 } }
```
## include
Include related records:
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: true,
profile: true
}
})
```
### Filtered include
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: {
where: { published: true },
orderBy: { createdAt: 'desc' },
take: 5
}
}
})
```
### Nested include
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: {
include: {
comments: {
include: {
author: true
}
}
}
}
}
})
```
### Include relation count
```typescript
const users = await prisma.user.findMany({
include: {
_count: {
select: { posts: true, followers: true }
}
}
})
```
## omit
Exclude specific fields:
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
omit: {
password: true
}
})
// Returns all fields except password
```
### Omit in relations
```typescript
const users = await prisma.user.findMany({
omit: { password: true },
include: {
posts: {
omit: { content: true }
}
}
})
```
**Note:** Cannot use `select` and `omit` together.
## where
Filter records:
```typescript
const users = await prisma.user.findMany({
where: {
email: { contains: '@prisma.io' },
role: 'ADMIN'
}
})
```
See `filters.md` for detailed filter operators.
## orderBy
Sort results:
```typescript
// Single field
const users = await prisma.user.findMany({
orderBy: { name: 'asc' }
})
// Multiple fields
const users = await prisma.user.findMany({
orderBy: [
{ role: 'desc' },
{ name: 'asc' }
]
})
```
### Order by relation
```typescript
const users = await prisma.user.findMany({
orderBy: {
posts: { _count: 'desc' }
}
})
```
### Null handling
```typescript
const users = await prisma.user.findMany({
orderBy: {
name: { sort: 'asc', nulls: 'last' }
}
})
```
## take & skip
Pagination:
```typescript
// First page
const users = await prisma.user.findMany({
take: 10,
skip: 0
})
// Second page
const users = await prisma.user.findMany({
take: 10,
skip: 10
})
```
### Negative take (reverse)
```typescript
const lastUsers = await prisma.user.findMany({
take: -10,
orderBy: { id: 'asc' }
})
// Returns last 10 users
```
## cursor
Cursor-based pagination:
```typescript
// First page
const firstPage = await prisma.user.findMany({
take: 10,
orderBy: { id: 'asc' }
})
// Next page using cursor
const nextPage = await prisma.user.findMany({
take: 10,
skip: 1, // Skip the cursor record
cursor: { id: firstPage[firstPage.length - 1].id },
orderBy: { id: 'asc' }
})
```
## distinct
Return unique values:
```typescript
const cities = await prisma.user.findMany({
distinct: ['city'],
select: { city: true }
})
```
### Multiple distinct fields
```typescript
const locations = await prisma.user.findMany({
distinct: ['city', 'country']
})
```

View File

@ -0,0 +1,198 @@
# Raw Queries
Execute raw SQL when Prisma's query API isn't sufficient.
## $queryRaw
Execute SELECT queries and get typed results:
```typescript
const users = await prisma.$queryRaw`
SELECT * FROM "User" WHERE email LIKE ${'%@prisma.io'}
`
```
### With type
```typescript
type User = { id: number; email: string; name: string | null }
const users = await prisma.$queryRaw<User[]>`
SELECT id, email, name FROM "User" WHERE role = ${'ADMIN'}
`
```
### Dynamic table/column names
Use `Prisma.raw()` for identifiers (not safe for user input):
```typescript
import { Prisma } from '../generated/client'
const column = 'email'
const users = await prisma.$queryRaw`
SELECT ${Prisma.raw(column)} FROM "User"
`
```
### With Prisma.sql
Build queries dynamically:
```typescript
import { Prisma } from '../generated/client'
const email = 'alice@prisma.io'
const query = Prisma.sql`SELECT * FROM "User" WHERE email = ${email}`
const users = await prisma.$queryRaw(query)
```
### Join multiple SQL fragments
```typescript
import { Prisma } from '../generated/client'
const conditions = [
Prisma.sql`role = ${'ADMIN'}`,
Prisma.sql`verified = ${true}`
]
const users = await prisma.$queryRaw`
SELECT * FROM "User"
WHERE ${Prisma.join(conditions, ' AND ')}
`
```
## $executeRaw
Execute INSERT, UPDATE, DELETE (returns affected count):
```typescript
const count = await prisma.$executeRaw`
UPDATE "User" SET verified = true WHERE email LIKE ${'%@prisma.io'}
`
console.log(`Updated ${count} users`)
```
### Delete example
```typescript
const deleted = await prisma.$executeRaw`
DELETE FROM "User" WHERE "deletedAt" < ${thirtyDaysAgo}
`
```
### Insert example
```typescript
const inserted = await prisma.$executeRaw`
INSERT INTO "Log" (message, level, timestamp)
VALUES (${message}, ${level}, ${new Date()})
`
```
## $queryRawUnsafe / $executeRawUnsafe
For fully dynamic queries (use with caution!):
```typescript
// ⚠️ SQL injection risk - only use with trusted input
const table = 'User'
const users = await prisma.$queryRawUnsafe(
`SELECT * FROM "${table}" WHERE id = $1`,
userId
)
```
### Parameterized unsafe query
```typescript
const result = await prisma.$executeRawUnsafe(
'UPDATE "User" SET name = $1 WHERE id = $2',
'Alice',
1
)
```
## SQL Injection Prevention
### Safe (parameterized)
```typescript
// ✅ User input is parameterized
const email = userInput
const users = await prisma.$queryRaw`
SELECT * FROM "User" WHERE email = ${email}
`
```
### Unsafe (concatenation)
```typescript
// ❌ SQL injection vulnerability!
const email = userInput
const users = await prisma.$queryRawUnsafe(
`SELECT * FROM "User" WHERE email = '${email}'`
)
```
## Database-Specific Features
### PostgreSQL
```typescript
// Array operations
const users = await prisma.$queryRaw`
SELECT * FROM "User" WHERE 'admin' = ANY(roles)
`
// JSON operations
const users = await prisma.$queryRaw`
SELECT * FROM "User" WHERE metadata->>'theme' = 'dark'
`
```
### MySQL
```typescript
// Full-text search
const posts = await prisma.$queryRaw`
SELECT * FROM Post WHERE MATCH(title, content) AGAINST(${searchTerm})
`
```
## Transactions with Raw Queries
```typescript
await prisma.$transaction(async (tx) => {
await tx.$executeRaw`UPDATE "Account" SET balance = balance - ${amount} WHERE id = ${senderId}`
await tx.$executeRaw`UPDATE "Account" SET balance = balance + ${amount} WHERE id = ${recipientId}`
})
```
## Handling Results
### BigInt handling
PostgreSQL returns BigInt for COUNT:
```typescript
const result = await prisma.$queryRaw<[{ count: bigint }]>`
SELECT COUNT(*) as count FROM "User"
`
const count = Number(result[0].count)
```
### Date handling
```typescript
type Result = { createdAt: Date }
const users = await prisma.$queryRaw<Result[]>`
SELECT "createdAt" FROM "User"
`
// createdAt is already a Date object
```
Invalid JavaScript `Date` values passed to raw queries fail validation instead of being silently serialized as `null`. Validate date input at the application boundary; do not rely on `new Date(badValue)` reaching the database.
When a driver adapter returns an unmapped database-specific error, Prisma surfaces `P2039` with the adapter's preserved original code/message. If those details are missing, fix the adapter mapping rather than parsing rendered error text.

View File

@ -0,0 +1,308 @@
# Relation Queries
Query and modify related records.
## Include Relations
Load related records:
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: true,
profile: true
}
})
```
### Filtered include
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: {
where: { published: true },
orderBy: { createdAt: 'desc' },
take: 5,
select: { id: true, title: true }
}
}
})
```
### Nested include
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: {
include: {
comments: {
include: { author: true }
}
}
}
}
})
```
## Select Relations
```typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
select: {
name: true,
posts: {
select: { title: true }
}
}
})
```
## Nested Writes
### Create with relations
```typescript
const user = await prisma.user.create({
data: {
email: 'alice@prisma.io',
posts: {
create: [
{ title: 'Post 1' },
{ title: 'Post 2' }
]
},
profile: {
create: { bio: 'Hello!' }
}
}
})
```
### Create or connect
```typescript
const post = await prisma.post.create({
data: {
title: 'New Post',
author: {
connectOrCreate: {
where: { email: 'alice@prisma.io' },
create: { email: 'alice@prisma.io', name: 'Alice' }
}
}
}
})
```
### Connect existing
```typescript
const post = await prisma.post.create({
data: {
title: 'New Post',
author: {
connect: { id: 1 }
}
}
})
// Shorthand for foreign key
const post = await prisma.post.create({
data: {
title: 'New Post',
authorId: 1
}
})
```
## Update Relations
### Update related records
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: {
posts: {
update: {
where: { id: 1 },
data: { title: 'Updated Title' }
}
}
}
})
```
### Update many related
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: {
posts: {
updateMany: {
where: { published: false },
data: { published: true }
}
}
}
})
```
### Upsert related
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: {
profile: {
upsert: {
create: { bio: 'New bio' },
update: { bio: 'Updated bio' }
}
}
}
})
```
### Disconnect
```typescript
// 1-to-1 optional
const user = await prisma.user.update({
where: { id: 1 },
data: {
profile: { disconnect: true }
}
})
// Many-to-many
const post = await prisma.post.update({
where: { id: 1 },
data: {
tags: {
disconnect: [{ id: 1 }, { id: 2 }]
}
}
})
```
### Delete related
```typescript
const user = await prisma.user.update({
where: { id: 1 },
data: {
posts: {
delete: { id: 1 }
}
}
})
// Delete many
const user = await prisma.user.update({
where: { id: 1 },
data: {
posts: {
deleteMany: { published: false }
}
}
})
```
### Set (replace all)
```typescript
// Replace all related records
const post = await prisma.post.update({
where: { id: 1 },
data: {
tags: {
set: [{ id: 1 }, { id: 2 }]
}
}
})
```
## Relation Filters
### some
At least one matches:
```typescript
const users = await prisma.user.findMany({
where: {
posts: { some: { published: true } }
}
})
```
### every
All match:
```typescript
const users = await prisma.user.findMany({
where: {
posts: { every: { published: true } }
}
})
```
### none
None match:
```typescript
const users = await prisma.user.findMany({
where: {
posts: { none: { published: true } }
}
})
```
### is / isNot (1-to-1)
```typescript
const users = await prisma.user.findMany({
where: {
profile: { is: { country: 'USA' } }
}
})
```
## Count Relations
```typescript
const users = await prisma.user.findMany({
select: {
name: true,
_count: {
select: { posts: true, followers: true }
}
}
})
// { name: 'Alice', _count: { posts: 5, followers: 100 } }
```
### Filter counted relations
```typescript
const users = await prisma.user.findMany({
select: {
name: true,
_count: {
select: {
posts: { where: { published: true } }
}
}
}
})
```

Some files were not shown because too many files have changed in this diff Show More