diff --git a/content/200-orm/800-more/300-upgrade-guides/200-upgrading-versions/400-upgrading-to-prisma-7.mdx b/content/200-orm/800-more/300-upgrade-guides/200-upgrading-versions/400-upgrading-to-prisma-7.mdx new file mode 100644 index 0000000000..45ddd2dc22 --- /dev/null +++ b/content/200-orm/800-more/300-upgrade-guides/200-upgrading-versions/400-upgrading-to-prisma-7.mdx @@ -0,0 +1,323 @@ +--- +title: 'Upgrade to Prisma ORM 7' +metaTitle: 'Upgrade to Prisma ORM 7' +metaDescription: 'Guide on how to upgrade to Prisma ORM 7' +tocDepth: 3 +toc: true +--- + +Prisma ORM v7 introduces **breaking changes** when you upgrade from an earlier Prisma ORM version. This guide explains how this upgrade might affect your application and gives instructions on how to handle any changes. + +
+Questions answered in this page + +- What changed in Prisma 7? +- How do I upgrade safely? +- Which breaking changes affect my app? + +
+ +For developers using AI Agents, we have a [migration prompt](/docs/ai/prompts/prisma-7) that you can +add to your project for automatic migrations. + +## Upgrade the `prisma` and `@prisma/client` packages to v7 + +To upgrade to Prisma ORM v7 from an earlier version, you need to update both the `prisma` and `@prisma/client` packages: + + + + + +```terminal +npm install @prisma/client@7 +npm install -D prisma@7 +``` + + + + + +```terminal +yarn up prisma@7 @prisma/client@7 +``` + + + + + +```terminal +pnpm upgrade prisma@7 @prisma/client@7 +``` + + + + + +```terminal +bun add @prisma/client@7 +bun add prisma@7 --dev +``` + + + + + +:::danger + +Before you upgrade, check each breaking change below to see how the upgrade might affect your application. + +::: + +## Breaking changes + +This section gives an overview of breaking changes in Prisma ORM v7. + +### Minimum supported Node.js & TypeScript versions + +| | Minimum Version | Recommended | +|------------|-----------------|-------------| +| Node | 20.19.0 | 22.x | +| TypeScript | 5.4.0 | 5.9.x | + +### ESM support +Prisma ORM now ships as an ES module, the module format supported in Bun, Deno, and Node. Set the +`type` field in your `package.json` to `module` + +```json +{ + "type": "module", + "scripts": {...}, +} +``` + +If you are using TypeScript, you need to configure your `tsconfig.json` to be able to consume ES modules + +```json +{ + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "node", + "target": "ES2023", + "strict": true, + "esModuleInterop": true + } +} +``` + + +### Prisma schema changes + +The older `prisma-client-js` provider will be removed in future releases of Prisma ORM. Upgrade to +the new `prisma-client` provider which uses the new Rust-free client. This will give you faster +queries, smaller bundle size, and require less system resources when deployed to your server. + + +#### Before +```prisma +generator client { + provider = "prisma-client-js" + engineType = "binary" +} +``` + +#### After +```prisma +generator client { + provider = "prisma-client" +} +``` + +Additionally other fields such as `url`, `directUrl`, and `shadowDatabaseUrl` in the `datasource` block are deprecated and now part of the [Prisma Config](/orm/reference/prisma-config-reference) + +```ts +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + datasource: { + url: env('DATABASE_URL'), + directUrl: env('DIRECT_URL'), + shadowDatabaseUrl: env('SHADOW_DATABASE_URL') + }, +}) +``` + + +### Driver adapters and client instantiation +The way to create a new Prisma Client has changed to require a driver adapter for all databases. +This change aligns with the move to make the main Prisma Client as lean and open as possible. For +instance, if you are using Prisma Postgres, you now need the `@prisma/adapter-pg` adapter. This also +means the signature for creating a new Prisma Client has changed slightly: + +#### Before + +```ts +import { PrismaClient } from '@prisma/client'; +const prisma = new PrismaClient({ + datasources: { + db: { url: process.env.DATABASE_URL }, + }, + datasourceUrl: process.env.DATABASE_URL, +}); +``` + +#### After + +```ts +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 }); +``` + +If you are using SQLite, you can use the `@prisma/adapter-better-sqlite3`: + +```ts +import { PrismaClient } from './generated/prisma/client'; +import { PrismaBetterSQLite3 } from '@prisma/adapter-better-sqlite3'; + +const adapter = new PrismaBetterSQLite3({ + url: process.env.DATABASE_URL || 'file:./dev.db' +}) + +export const prisma = new PrismaClient({ adapter }) +``` + +### Explicit loading of environment variables +In Prisma ORM 7.0.0, environment variables are not loaded by default. Instead developers need to +explicitly load the variables when calling the `prisma` CLI. Libraries like [`dotenv`](https://github.com/motdotla/dotenv) can be used to manage loading environment variables by reading the appropriate `.env` file. + + + + + + +```terminal +npm install dotenv +``` + + + + + +```terminal +yarn add dotenv +``` + + + + + +```terminal +pnpm add dotenv +``` + + + + + +For bun users, no action is required as bun will automatically load `.env` files. + +### Prisma config is now used to configure the Prisma CLI + +Prisma Config is now the default place for configuring how the Prisma CLI interacts with your +database. You now configure your database URL, schema location, migration output, and custom seed +scripts. + +```ts +import 'dotenv/config' +import { defineConfig, env } from 'prisma/config' + +export default defineConfig({ + // the main entry for your schema + schema: 'prisma/schema.prisma', + // where migrations should be generated + // what script to run for "prisma db seed" + migrations: { + path: 'prisma/migrations', + seed: 'tsx prisma/seed.ts', + }, + // The database URL + datasource: { + // Type Safe env() helper + // Does not replace the need for dotenv + url: env('DATABASE_URL'), + }, +}) +``` + + + +### Metrics has been removed from the Client extensions + +The Metrics preview feature was deprecated in [Prisma ORM 6.14.0](https://github.com/prisma/prisma/releases/tag/6.14.0) and has been removed for Prisma ORM 7.0.0. +If you need this feature, you can use the underlying driver adapter for your database, or Client Extensions to make this information available. + +For example, a basic `totalQueries` counter: + +```ts +const total = 0 +const prisma = new PrismaClient().$extends({ + client: { + $log: (s: string) => console.log(s), + async $totalQueries() { return total; }, + }, + query: { + $allModels: { + async $allOperations({ query, args }) { + total += 1; + return query(args); + }, + }, + }, +}) + +async function main() { + prisma.$log('Hello world') + const totalQueries = await prisma.$totalQueries() + console.log(totalQueries) +} +``` + +### Client middleware has been removed + +The client middleware API has been removed. If possible, use [Client Extensions](orm/prisma-client/client-extensions). + +```ts +// ❌ Old (removed) +prisma.$use(async (params, next) => { + // middleware logic + return next(params) +}) +// ✅ New (use extensions) +const prisma = new PrismaClient().$extends({ + query: { + user: { + async findMany({ args, query }) { + // extension logic + return query(args) + } + } + } +}) +``` + +### Various environment variables have been removed + +We've removed a small selection of Prisma-specific environment variables. + +- `PRISMA_CLI_QUERY_ENGINE_TYPE` +- `PRISMA_CLIENT_ENGINE_TYPE` +- `PRISMA_QUERY_ENGINE_BINARY` +- `PRISMA_QUERY_ENGINE_LIBRARY` +- `PRISMA_GENERATE_SKIP_AUTOINSTALL` +- `PRISMA_SKIP_POSTINSTALL_GENERATE` +- `PRISMA_GENERATE_IN_POSTINSTALL` +- `PRISMA_GENERATE_DATAPROXY` +- `PRISMA_GENERATE_NO_ENGINE` +- `PRISMA_CLIENT_NO_RETRY` +- `PRISMA_MIGRATE_SKIP_GENERATE` +- `PRISMA_MIGRATE_SKIP_SEED` diff --git a/content/200-orm/800-more/300-upgrade-guides/200-upgrading-versions/index.mdx b/content/200-orm/800-more/300-upgrade-guides/200-upgrading-versions/index.mdx index a207ab3508..4300d785ec 100644 --- a/content/200-orm/800-more/300-upgrade-guides/200-upgrading-versions/index.mdx +++ b/content/200-orm/800-more/300-upgrade-guides/200-upgrading-versions/index.mdx @@ -24,6 +24,7 @@ To upgrade to the latest version of Prisma ORM: ### Prisma ORM 2 and onwards +- [Upgrade to Prisma ORM 7](/orm/more/upgrade-guides/upgrading-versions/upgrading-to-prisma-7) - [Upgrade to Prisma ORM 6](/orm/more/upgrade-guides/upgrading-versions/upgrading-to-prisma-6) - [Upgrade to Prisma ORM 5](/orm/more/upgrade-guides/upgrading-versions/upgrading-to-prisma-5) - [Upgrade to Prisma ORM 4](/orm/more/upgrade-guides/upgrading-versions/upgrading-to-prisma-4) diff --git a/content/900-ai/prompts/prisma-7.mdx b/content/900-ai/prompts/prisma-7.mdx new file mode 100644 index 0000000000..ed87b17683 --- /dev/null +++ b/content/900-ai/prompts/prisma-7.mdx @@ -0,0 +1,298 @@ +--- +title: 'Migrating to Prisma 7' +metaTitle: 'How to upgrade to Prisma ORM version 7' +description: 'Step-by-step guide for migration your app to use the version 7 of Prisma ORM' +sidebar_label: 'Prisma 7 Migration' +--- + +## How to use + +Include this prompt in your AI assistant to guide in upgrading to Prisma ORM 7.0. + +- **GitHub Copilot**: Type `#` to reference the prompt file. +- **Cursor**: Use `@Files` and select your prompt file. +- **Zed**: Use `/file` followed by your prompt's path. +- **Windsurf**: Use `@Files` and choose your prompt file from the list. + +## Prompt + +````md +--- +# Specify the following for Cursor rules +description: Guidelines for migrating an app to Prisma ORM v7 +alwaysApply: false +--- + +# Prisma v6 → v7 Migration Assistant + +**Role:** You are a precise, changeset-oriented code migration assistant. Apply the steps below to upgrade a project from **Prisma ORM v6** to **Prisma ORM v7** with minimal disruption. Work in small, re-viewable steps and explain each change briefly. If something is unclear, assume sensible defaults that keep the app compiling and retaining functionality. + +## Ground Rules + +- Never introduce Prisma Accelerate or HTTP/WebSocket drivers on your own. +- Do **not** remove Prisma Accelerate automatically. +- **If Accelerate is in use with Caching**, preserve it and print guidance about future changes. +- **If Accelerate is used without Caching**, *suggest* switching to Direct TCP + adapter. +- Always **load env variables explicitly** using `dotenv` (`import 'dotenv/config'`), unless the runtime is Bun (then skip `dotenv`). +- Keep TypeScript **ESM** compatible, and avoid CommonJS requires. +- Favor additive, reversible edits; do not remove user logic. +- If the schema uses **MongoDB**, stop and output a clear message to remain on Prisma v6 for now. + +--- + +## 0) Detect Context & Plan + +1. Identify: + - Package manager and scripts. + - Database: Postgres, SQLite, MySQL, SQL Server (MongoDB = halt). + - Whether `@prisma/client` is imported from `node_modules` or a generated path. + - Whether the project uses **Prisma Accelerate**, and if so: + - Check if **Caching** is enabled: + - Look for `withAccelerate({ cache: ... })` + - Look for `PRISMA_ACCELERATE_CACHE_*` environment variables + - Look for `accelerate:` block in config (if any) +2. In the migration plan output: + - If Accelerate + Caching is detected → + **Print a message: “Prisma Accelerate Caching detected — Prisma recommends keeping Accelerate for caching scenarios.”** + - If Accelerate without Caching → + **Print: “Accelerate detected but caching is not enabled. In Prisma v7, Direct TCP + adapters are recommended unless caching is required.”** + - If no Accelerate → continue normally. + +> **Do not modify or remove Accelerate code paths. Only describe recommendations.** + +--- + +## 1) Dependencies + +- Upgrade/install: + - Dev: `prisma@latest` (7.0.0), `tsx`, `dotenv` (skip if Bun). + - Runtime: `@prisma/client@latest` (7.0.0). + - **One** database adapter that matches the datasource: + - Postgres: `@prisma/adapter-ppg` + - SQLite: `@prisma/adapter-better-sqlite3` + - MySQL/mariaDB: `@prisma/adapter-mariadb` + - D1: `@prisma/adapter-d1` + - PlanetScale: `@prisma/adapter-planetscale` + - MSSQL: `@prisma/adapter-mssql` + - CockroachDB: `@prisma/adapter-pg` + - Neon: `@prisma/adapter-neon` + +- **Do not remove Accelerate packages automatically.** +- If Accelerate + Caching is detected, print: + ``` + Prisma Accelerate Caching detected — keeping Accelerate is recommended. + ``` +- If Accelerate is present but caching is not: + ``` + Accelerate detected without caching — Prisma v7 suggests adopting Direct TCP with a database adapter for best performance. + ``` +- Eliminate no user code; only output informational guidance. + +> Produce installation commands based on the repo’s package manager. + +--- + +## 2) Prisma Schema Changes + +- In `schema.prisma`: + + - `generator client`: + + ```diff + - provider = "prisma-client-js" + + provider = "prisma-client" + output = "./generated" + ``` + + - Remove any `previewFeatures = ["driverAdapters"]` and any `engineType` attributes. + + - Update the `datasource db` block: + + - **Goal:** keep the existing `provider` value, but **remove any `url = …` entry**. + + - Example (for illustration only — do not insert comments into the user's schema): + + - Before: + + ```prisma + datasource db { + provider = "postgresql" + url = env("DATABASE_URL") + } + ``` + + - After: + + ```prisma + datasource db { + provider = "postgresql" + } + ``` + + - Rules: + + - Preserve the existing `provider` value exactly as-is (e.g. `"postgresql"`, `"mysql"`, `"sqlite"`, etc.). + - Remove only the `url = ...` line from the `datasource db` block. + - Preserve any other properties on the datasource (for example: `shadowDatabaseUrl`, `relationMode`, `schemas`, `extensions`, `directUrl`, etc.). + - Do **not** add explanatory comments into the schema; comments in this prompt are hints for you, not code to emit. + +- After edits, run `prisma generate`. + +--- + +## 3) Introduce prisma.config.ts Create **prisma.config.ts** at repo root (or prisma.config.mjs), centralizing Prisma CLI config and env management: + +```tsx +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: { + // Prefer DIRECT TCP via DATABASE_URL + url: env('DATABASE_URL'), + // Optionally support shadow DB if present: + // shadowDatabaseUrl: env('SHADOW_DATABASE_URL'), + }, +}) +``` + +- Remove any prisma.seed from package.json (the config above replaces it). + +--- + +## 4) ESM & TS Baseline - Ensure **package.json**: +```json + { + "type": "module", + "scripts": { + "dev": "tsx src/index.ts", + "generate": "prisma generate", + "migrate": "prisma migrate dev", + "build": "tsc -p tsconfig.json" + } + } +``` + +- Ensure **tsconfig.json** supports ESM: + +```json + { + "compilerOptions": { + "module": "ESNext", + "moduleResolution": "Node", + "target": "ES2023", + "strict": true, + "esModuleInterop": true + } + } +``` +--- + +## 5) Refactor Client Import & Construction + +If Prisma Accelerate is detected: + +- If caching is enabled → **preserve the existing Accelerate setup**. +- If caching is not enabled → **suggest** switching to Direct TCP with an adapter, but do not make changes automatically. + +Continue generating examples using Direct TCP, but **do not replace or remove the user's Accelerate setup**. + +--- + +## 6) Seeding Script Update - Ensure prisma/seed.ts uses the same **adapter** and **dotenv** import as runtime: + +```tsx + import 'dotenv/config' + import { PrismaClient } from '../generated/prisma/client.js' + import { PrismaPg } from '@prisma/adapter-pg' + + const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL! }) + const prisma = new PrismaClient({ adapter }) + + // seed… +``` +- Set seed command via prisma.config.ts (no package.json#prisma.seed). + +--- + +## 7) Middleware → Extensions + +- If prisma.$use middleware exists, inform users that the API has been removed + +--- + +## 8) Accelerate Messaging + +### 🟩 If Accelerate Caching is detected + +``` +Prisma Accelerate Caching detected. +Prisma v7 fully supports caching scenarios via Accelerate. +Your existing Accelerate setup will be preserved. +``` + +### 🟨 If Accelerate is present but caching is NOT detected + +``` +Prisma Accelerate detected without caching. + +Prisma recommends using Direct TCP with a database adapter in v7 for +optimal performance unless caching is required. + +Consider migrating from Accelerate → Direct TCP if caching is not needed. +(No code changes were applied automatically.) +``` + +### 🟦 If Accelerate is not detected at all + +``` +Direct TCP is the recommended default for Prisma v7. +Your project will be migrated accordingly using the appropriate adapter. +``` + +--- + +## 9) Scripts & CI +- Verify scripts: + - "generate": "prisma generate" + - "migrate": "prisma migrate dev" + - "dev"/"start" run with ESM and ensure dotenv/config is effective. +- In CI, ensure Node **≥ 20.19** and TypeScript **≥ 5.4**. + +--- +## 10) Run & Verify + +1. prisma generate → should succeed and emit client to ./generated. +2. prisma migrate dev → runs against DATABASE_URL (direct TCP). +3. tsx prisma/seed.ts → inserts sample record(s) cleanly. +4. App boot: instantiate PrismaClient with adapter; confirm queries work. +5. If **P1017 / connection** errors: - Confirm DATABASE_URL and network reachability. - Confirm import 'dotenv/config' executes early. +6. If **module resolution** errors: - Confirm "type": "module", ESM imports, and re-generate client. + +--- + +## Safety Checks & Edge Cases +- **MongoDB provider** detected → stop and recommend staying on Prisma 6 until v7 MongoDB support returns. +- **Multiple entrypoints** (workers, scripts, tests): apply the same client/adapter/dotenv pattern everywhere. +- **Typed SQL** or custom extensions: keep as-is; ensure they compile after client re-generation. +- Preserve existing output path if the project uses custom locations. + +--- + +## Deliverables + +- A short **CHANGELOG** summary in the PR body: + - Dependency bumps and added adapter + - Schema generator change + - New `prisma.config.ts` + - Runtime refactor to adapter + optional Accelerate messaging + - ESM/TS config updates + - Seed script updates + - No automatic removal of Accelerate + +```` diff --git a/sidebars.ts b/sidebars.ts index e38be5d27a..c44f248752 100644 --- a/sidebars.ts +++ b/sidebars.ts @@ -534,7 +534,7 @@ const sidebars: SidebarsConfig = { label: "Prompts", collapsed: false, collapsible: false, - items: ["ai/prompts/astro", "ai/prompts/nextjs"], + items: ["ai/prompts/astro", "ai/prompts/nextjs", "ai/prompts/prisma-7"], }, { type: "category",