diff --git a/content/200-orm/200-prisma-client/000-setup-and-configuration/005-introduction.mdx b/content/200-orm/200-prisma-client/000-setup-and-configuration/005-introduction.mdx index 061779c21d..e7520935fd 100644 --- a/content/200-orm/200-prisma-client/000-setup-and-configuration/005-introduction.mdx +++ b/content/200-orm/200-prisma-client/000-setup-and-configuration/005-introduction.mdx @@ -138,17 +138,6 @@ const prisma = new PrismaClient() > **Note**: If you're using [driver adapters](/orm/overview/databases/database-drivers#driver-adapters), you can import from the location spefified in your generator's `output` path directly, e.g. `./src/generated/prisma`. No need to import from `./src/generated/prisma/edge`. -For Deno, you can import Prisma Client as follows: - -```ts file=lib/prisma.ts -import { PrismaClient } from './generated/prisma/deno/edge.ts' - -const prisma = new PrismaClient() -// use `prisma` in your application to read and write data in your DB -``` - -The import path will depend on the custom `output` specified in Prisma Client's [`generator`](/orm/reference/prisma-schema-reference#generator) block in your Prisma schema. - ### 4. Use Prisma Client to send queries to your database Once you have instantiated `PrismaClient`, you can start sending queries in your code: diff --git a/content/200-orm/200-prisma-client/500-deployment/301-edge/550-deploy-to-deno-deploy.mdx b/content/200-orm/200-prisma-client/500-deployment/301-edge/550-deploy-to-deno-deploy.mdx index f2c1ab874b..0ad4f8d407 100644 --- a/content/200-orm/200-prisma-client/500-deployment/301-edge/550-deploy-to-deno-deploy.mdx +++ b/content/200-orm/200-prisma-client/500-deployment/301-edge/550-deploy-to-deno-deploy.mdx @@ -47,14 +47,17 @@ This command: - Creates a `prisma` directory containing a `schema.prisma` file for your database models. - Creates a `.env` file with your `DATABASE_URL` (e.g., for Prisma Postgres it should have something similar to `DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI..."`). -Edit the `prisma/schema.prisma` file to define a `Log` model, add a custom `output` path and enable the `deno` preview feature flag: +Edit the `prisma/schema.prisma` file to define a `Log` model, add a custom `output` path and [the `prisma-client` generator](/orm/prisma-schema/overview/generators#prisma-client-early-access) with `deno` as the `runtime`: ```prisma file=schema.prisma highlight=3-4,12-23;add showLineNumbers generator client { + // delete-start provider = "prisma-client-js" + // delete-end //add-start - previewFeatures = ["deno"] - output = "../generated/client" + provider = "prisma-client" + output = "../generated/prisma" + runtime = "deno" //add-end } @@ -79,13 +82,11 @@ enum Level { //add-end ``` -:::note +Then, install Prisma Client: -To use Deno, you need to add the preview feature flag `deno` to the `generator` block of your `schema.prisma` file. - -Deno also requires you to generate Prisma Client in a custom location. You can enable this with the `output` parameter in the `generator` block. - -::: +```terminal +deno install npm:@prisma/client +``` Then, install [the Client extension](https://www.npmjs.com/package/@prisma/extension-accelerate) required to use Prisma Postgres: @@ -121,7 +122,7 @@ You can now create a local Deno application. Create `index.ts` in the root folde ```ts file=index.ts import { serve } from "https://deno.land/std@0.140.0/http/server.ts"; import { withAccelerate } from "npm:@prisma/extension-accelerate"; -import { PrismaClient } from "./generated/client/deno/edge.ts"; +import { PrismaClient } from "./generated/prisma/client.ts"; const prisma = new PrismaClient().$extends(withAccelerate()); @@ -208,6 +209,7 @@ Use the GitHub repository to add your application to Deno Deploy: 1. Go to [https://dash.deno.com/](https://dash.deno.com/). 1. Select a GitHub organization or user and then select a repository. 1. Select a production branch and select **Fresh (Automatic)** mode so that Deno Deploy can deploy every time you push a change to the repository. +1. In the **Build Step** add `deno run -A npm:prisma generate` to generate the Prisma Client. 1. Select `index.ts` as the entry point to your project. 1. Click `Create & Deploy`. @@ -227,7 +229,7 @@ Add the following code in your `index.ts` file: ```ts file=index.ts import { serve } from "https://deno.land/std@0.140.0/http/server.ts"; import { withAccelerate } from "npm:@prisma/extension-accelerate"; -import { PrismaClient } from "./generated/client/deno/edge.ts"; +import { PrismaClient } from "./generated/prisma/client.ts"; const prisma = new PrismaClient().$extends(withAccelerate()); diff --git a/content/200-orm/500-reference/200-prisma-cli-reference.mdx b/content/200-orm/500-reference/200-prisma-cli-reference.mdx index 31112e07cc..6cd2bbbb1d 100644 --- a/content/200-orm/500-reference/200-prisma-cli-reference.mdx +++ b/content/200-orm/500-reference/200-prisma-cli-reference.mdx @@ -328,6 +328,53 @@ A file to define environment variables for your project: DATABASE_URL="mysql://user:password@localhost:3306/mydb" ``` +### `dev` + +The `dev` command starts a local Prisma Postgres database that you can run Prisma ORM commands against. It is useful for development and testing purposes and also allows you to switch to [Prisma Postgres](/postgres) in production easily. You can learn more about the local Prisma Postgres database [in this section](/postgres/database/local-development). + +#### Arguments + +| Argument | Required | Description | Default | +| --------------------- | -------- | ------------------------------------------------------------------------------------------------------------------- | ------- | +| `--port` (or `-p`) | No | Main port number the local Prisma Postgres HTTP server will listen on. | `51213` | +| `--db-port` (or `-P`) | No | Port number the local Prisma Postgres database server will listen on. | `51214` | +| `--shadow-db-port` | No | Port number the shadow database server will listen on. | `51215` | +| `--debug` | No | Enable debug logging. | `false` | + + + +#### Examples + +**Run `prisma dev`** + + + + + +```terminal +prisma dev +``` + + + + + +```code no-copy wrap +Starting Prisma Dev... + + +Great Success! + +To connect to your local Prisma Postgres database via Prisma ORM, use the following connection string: + + DATABASE_URL="prisma+postgres://localhost:51213/?api_key=__API_KEY__" + +``` + + + + + ### `generate` The `generate` command generates assets like Prisma Client based on the [`generator`](/orm/prisma-schema/overview/generators) and [`data model`](/orm/prisma-schema/data-model/models) blocks defined in your `prisma/schema.prisma` file. diff --git a/content/200-orm/500-reference/500-preview-features/050-client-preview-features.mdx b/content/200-orm/500-reference/500-preview-features/050-client-preview-features.mdx index 9e2168cc5d..e5a1c79de7 100644 --- a/content/200-orm/500-reference/500-preview-features/050-client-preview-features.mdx +++ b/content/200-orm/500-reference/500-preview-features/050-client-preview-features.mdx @@ -21,7 +21,6 @@ The following [Preview](/orm/more/releases#preview) feature flags are available | [`metrics`](/orm/prisma-client/observability-and-logging/metrics) | [3.15.0](https://github.com/prisma/prisma/releases/tag/3.15.0) | [Submit feedback](https://github.com/prisma/prisma/issues/13579) | | [`multiSchema`](https://github.com/prisma/prisma/issues/1122#issuecomment-1231773471) | [4.3.0](https://github.com/prisma/prisma/releases/tag/4.3.0) | [Submit feedback](https://github.com/prisma/prisma/issues/15077) | | [`postgresqlExtensions`](/orm/prisma-schema/postgresql-extensions) | [4.5.0](https://github.com/prisma/prisma/releases/tag/4.5.0) | [Submit feedback](https://github.com/prisma/prisma/issues/15835) | -| [`deno`](/orm/prisma-client/deployment/edge/deploy-to-deno-deploy) | [4.5.0](https://github.com/prisma/prisma/releases/tag/4.5.0) | [Submit feedback](https://github.com/prisma/prisma/issues/15844) | | [`views`](/orm/prisma-schema/data-model/views) | [4.9.0](https://github.com/prisma/prisma/releases/tag/4.9.0) | [Submit feedback](https://github.com/prisma/prisma/issues/17335) | | `driverAdapters` | [5.4.0](https://github.com/prisma/prisma/releases/tag/5.4.0) | [Submit feedback](https://github.com/prisma/prisma/issues/3108) | | `relationJoins` | [5.7.0](https://github.com/prisma/prisma/releases/tag/5.7.0) | [Submit feedback](https://github.com/prisma/prisma/discussions/22288) | @@ -30,7 +29,7 @@ The following [Preview](/orm/more/releases#preview) feature flags are available | `strictUndefinedChecks` | [5.20.0](https://github.com/prisma/prisma/releases/tag/5.20.0) | [Submit feedback](https://github.com/prisma/prisma/discussions/25271) | | [`fullTextSearchPostgres`](/orm/prisma-client/queries/full-text-search) | [6.0.0](https://github.com/prisma/prisma/releases/tag/6.0.0) | [Submit feedback](https://github.com/prisma/prisma/issues/25773) | | [`prisma-client`](/orm/prisma-schema/overview/generators#prisma-client-early-access) | [6.6.0](https://pris.ly/release/6.6.0) | [Submit feedback](https://github.com/prisma/prisma/issues/25773) | -| `queryCompiler` | [6.7.0](https://pris.ly/release/6.7.0) | [Submit feedback](https://github.com/prisma/prisma/issues/tbd) | +| `queryCompiler` | [6.7.0](https://pris.ly/release/6.7.0) | [Submit feedback](https://github.com/prisma/prisma/issues/) | To enable a Preview feature, [add the feature flag to the `generator` block](#enabling-a-prisma-client-preview-feature) in your `schema.prisma` file. [Share your feedback on all Preview features on GitHub](https://github.com/prisma/prisma/issues/3108). diff --git a/content/200-orm/800-more/350-ai-tools/400-github-copilot.mdx b/content/200-orm/800-more/350-ai-tools/400-github-copilot.mdx new file mode 100644 index 0000000000..62c796e63d --- /dev/null +++ b/content/200-orm/800-more/350-ai-tools/400-github-copilot.mdx @@ -0,0 +1,234 @@ +--- +title: 'GitHub Copilot' +metaTitle: 'Prisma ORM with GitHub Copilot' +metaDescription: 'Learn about the features available with GitHub Copilot and Prisma ORM, plus best practices and tips.' +tocDepth: 3 +toc: true +--- + +GitHub Copilot is an AI coding assistant that speeds up your Prisma ORM workflows, so you spend less time on boilerplate and more on data modeling, querying, and collaboration. With the GitHub Copilot extension in your editor, you can: + +- Get Prisma-aware code suggestions as you edit your schema or invoke the client. +- Chat with Copilot about modeling patterns, troubleshoot queries, or explore migration strategies. +- Run common Prisma CLI commands (e.g. `prisma migrate dev`, `prisma db push`) via Copilot's command-palette interface. +- Scaffold Prisma schema models and generate Prisma Client code and run migrations directly from the Copilot chat interface. + +GitHub Copilot allows you to query the official docs via the [**Prisma for GitHub Copilot** extension](https://github.com/apps/prisma-for-github-copilot) and also perform automated [actions in VS Code Agent mode](/postgres/integrations/vscode-agent), such as scaffolding a Prisma schema, running seeds scripts, and creating a production-ready Prisma Postgres database. + +## Query Prisma docs with the Prisma for GitHub Copilot extension + +The [Prisma for GitHub Copilot extension](https://github.com/apps/prisma-for-github-copilot) lets you fetch Prisma documentation directly in GitHub Copilot Chat. You can look up schema syntax, client methods, migration commands, and more from your editor. + +### How to enable the extension + +1. Install the **Prisma for Copilot** from the GitHub Marketplace. +2. Ensure [GitHub Copilot Chat is installed](https://docs.github.com/en/copilot/using-github-copilot/copilot-chat/asking-github-copilot-questions-in-your-ide) and active in your code editor. +3. Open a file in your workspace and launch Copilot Chat. +4. In chat, prefix your question with the `@prisma-for-copilot` keyword: + +``` +@prisma-for-copilot How do I define a one-to-many relation? +``` + +1. Install the [Prisma for GitHub Copilot](https://github.com/apps/prisma-for-github-copilot) extension. +2. Open your IDE. +3. Install the [GitHub Copilot Chat extension](https://docs.github.com/en/copilot/managing-copilot/configure-personal-settings/installing-the-github-copilot-extension-in-your-environment). +4. Open Copilot Chat and switch to [**Ask** mode](https://code.visualstudio.com/docs/copilot/chat/chat-ask-mode). +5. Ask: "`@prisma-for-github-copilot` How do I define a one-to-many relation?" (If the `@prisma-for-github-copilot` namespace doesn't show up after a few seconds, reload the chat.) +6. When prompted, authorize the Prisma app in your browser, then return to the chat. +7. After returning to the chat, resend the question. +8. Copilot returns the answer pulled straight from the Prisma docs. + +## Use GitHub Copilot's agent features + +GitHub Copilot Chat offers an **Agent** mode in VS Code that can run Prisma commands. You can use the agent chat to: + +- Run and inspect migrations. +- Generate Prisma Client code. +- Create a new Prisma Postgres database and update your `.env` file. + +You can type `Create a database named test-db and add its connection string to the .env file.` in the Copilot chat, and it will automatically create a new database named `test-db` and add the connection string to your `.env` file. To learn more about this, visit our [VS Code agent mode documentation](/postgres/integrations/vscode-agent). + +## Customize GitHub Copilot with `copilot-instructions.md` + +You can tailor Copilot Chat's behavior in your repository by [adding a `.github/copilot-instructions.md` file](https://docs.github.com/en/copilot/customizing-copilot/adding-repository-custom-instructions-for-github-copilot). This file injects your guidelines into every Copilot Chat session. + +
+Example `.github/copilot-instructions.md` for Prisma + +```text +# GitHub Copilot Instructions for Prisma Workspace + +## General Guidelines + +1. **Language**: English only. +2. **Types**: Declare explicit types; avoid `any`. +3. **Comments**: Use JSDoc for public methods and classes. +4. **Exports**: One export per file. +5. **Naming**: + + * **Classes/interfaces** → `PascalCase` + * **Variables/functions** → `camelCase` + * **Files/directories** → `kebab-case` + * **Constants** → `UPPERCASE` + * **Boolean flags** → verb-based (e.g., `isLoading`) + +--- + +## Prisma-Specific Guidelines + +### 1. Data Modeling + +* **Domain-driven model names**: keep them singular (e.g. `User`, `OrderItem`). +* **Field naming**: use `camelCase` for fields (e.g. `createdAt`, `deletedAt`). +* **IDs & keys**: + + ```prisma + model Post { + id Int @id @default(autoincrement()) + uuid String @unique @default(uuid()) + } + /``` +* **Composite keys & uniques**: + + ```prisma + @@id([userId, role]) + @@unique([email, tenantId]) + /``` +* **Enums & constrained values**: leverage `enum` for fixed domains. +* **Soft deletes & audit**: + + ```prisma + model Base { + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + deletedAt DateTime? + } + /``` + +### 2. Indexing & Constraints + +* **Single-column indexes** for frequent lookups: + + ```prisma + @@index([email]) + /``` +* **Compound indexes** for multi-field filters/sorts: + + ```prisma + @@index([status, createdAt]) + /``` +* **Full-text search** (Postgres-only): + + ```prisma + @@index([title, content], type: Brin) // or Gin for JSONB + /``` + +### 3. Migrations + +* **Descriptive names**: `npx prisma migrate dev --name add-order-totals` +* **Idempotent steps**: avoid imperative SQL in migrations. +* **Shadow database**: enable in CI to catch drift. +* **Never edit** migration SQL after it’s applied to any environment. + +### 4. Client Instantiation & Connection Management + +* **Singleton pattern** + + ```ts + // prisma.ts + import { PrismaClient } from '@prisma/client'; + export const prisma = global.prisma || new PrismaClient(); + if (process.env.NODE_ENV !== 'production') global.prisma = prisma; + /``` + +### 5. Transactions & Batch Operations + +* **Multi-step atomicity**: + + ```ts + const result = await prisma.$transaction([ + prisma.user.create({ data: { /*…*/ } }), + prisma.order.create({ data: { /*…*/ } }), + ]); + /``` +* **Interactive transactions** for long-running flows. +* **Bulk writes**: chunk large inserts/updates to avoid timeouts. + +### 6. Precise Queries & Performance + +* **Select only needed fields**: + + ```ts + await prisma.user.findUnique({ + where: { id }, + select: { id: true, email: true }, + }); + /``` +* **Avoid N+1**: use `include` or batch `findMany` with `where: { id: { in: [...] } }` or use database joins in prisma. +* Use **Cursor-based pagination** + +### 7. Raw Queries & Client Extensions + +* **Raw SQL** when necessary, safely: + + ```ts + const users = await prisma.$queryRaw`SELECT * FROM "User" WHERE email = ${email}`; + /``` +* **Sanitize inputs** with `Prisma.sql` for complex interpolations. +* **Client extensions**: use preview feature `clientExtensions` to add common helper methods. + +### 8. Error Handling + +* **Catch specific errors**: + + ```ts + try { + // … + } catch (e) { + if (e instanceof Prisma.PrismaClientKnownRequestError) { + // P2002: Unique constraint + } + } + /``` +* **Wrap in service-level errors** to add context before bubbling up. + +### 9. Testing + +* **In-memory DB** (SQLite) or **Testcontainers** for integration tests. +* **Mock Prisma Client** for pure unit tests via `jest.mock()` or similar. + +### 10. Logging, Monitoring & Metrics + +* **Enable query logging** in dev: + + ```ts + new PrismaClient({ log: ['query', 'warn', 'error'] }); + /``` +* **APM integration** (Datadog, Sentry) – capture latency, errors. +* **Client extensions** for metrics: create extensions that wrap calls to emit timing and telemetry instead of middleware. + +### 11. Security & Best Practices + +* **Never expose** raw Prisma client in HTTP controllers—wrap in a service layer. +* **Validate inputs** (e.g. with Zod) before any DB operation. +* **Least privilege** DB users: use separate roles for migrations vs. runtime. +* **Rotate credentials** and load from secure vault (AWS Secrets Manager, etc.). + +### 12. Environment & Configuration + +* **Centralize `DATABASE_URL`** and connection settings in `.env`. +* **Pin preview features** in `schema.prisma`: + + ```prisma + generator client { + previewFeatures = ["clientExtensions", "interactiveTransactions"] + } + /``` +* **Version pinning**: match CLI and client versions in `package.json`. + +``` + +
+ +Place this file at the root of your repository under `.github/`. Copilot Chat automatically applies these rules to every conversation in your project. diff --git a/content/200-orm/800-more/500-development-environment/200-editor-setup.mdx b/content/200-orm/800-more/500-development-environment/200-editor-setup.mdx index d17879d216..eeeccb8c70 100644 --- a/content/200-orm/800-more/500-development-environment/200-editor-setup.mdx +++ b/content/200-orm/800-more/500-development-environment/200-editor-setup.mdx @@ -17,6 +17,13 @@ If you don't see your editor here, please [open a feature request](https://githu You can install the official [Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma). Once installed, make sure to select the appropriate language model to use it within VS Code. +:::tip + +If you're using VS Code, you can use [VS Code agent mode](https://code.visualstudio.com/docs/copilot/chat/chat-agent-mode) to enter prompts such as “create Postgres database” or “apply schema migration” directly in the chat. The VS code agent handles all underlying Prisma CLI invocations and API calls automatically. See our [VS Code Agent documentation](/postgres/integrations/vscode-agent) for more details. + +::: + + ## Community projects > **Note**: Community projects are not maintained or officially supported by Prisma and some features may by out of sync. Use at your own discretion. diff --git a/content/250-postgres/1100-integrations/400-mcp-server.mdx b/content/250-postgres/1100-integrations/400-mcp-server.mdx index 67cfde24cd..f1ecb6a0f8 100644 --- a/content/250-postgres/1100-integrations/400-mcp-server.mdx +++ b/content/250-postgres/1100-integrations/400-mcp-server.mdx @@ -14,6 +14,13 @@ The Prisma MCP server is available via the Prisma CLI command `prisma platform m ::: +:::tip + +If you're using VS Code, you can use [VS Code agent mode](https://code.visualstudio.com/docs/copilot/chat/chat-agent-mode) to enter prompts such as “create Postgres database” or “apply schema migration” directly in the chat. The VS code agent handles all underlying Prisma CLI invocations and API calls automatically. See our [VS Code Agent documentation](/postgres/integrations/vscode-agent) for more details. + +::: + + ## Usage The Prisma MCP server follows the standard JSON-based configuration for MCP servers. Here's what it looks like: diff --git a/content/250-postgres/1100-integrations/500-vscode-agent.mdx b/content/250-postgres/1100-integrations/500-vscode-agent.mdx new file mode 100644 index 0000000000..c20afede54 --- /dev/null +++ b/content/250-postgres/1100-integrations/500-vscode-agent.mdx @@ -0,0 +1,56 @@ +--- +title: 'VS Code Agent' +description: 'Simplify Prisma ORM workflows, manage migrations, and create databases using VS Code agent mode.' +metaTitle: 'VS Code Agent Mode' +metaDescription: 'Manage Prisma ORM migrations and provision Prisma databases efficiently using VS Code agent mode.' +tocDepth: 3 +toc: true +--- + +## Overview + +VS Code includes an [agent mode](https://pris.ly/vs-code-docs) (powered by GitHub Copilot) that automatically performs code changes and executes Prisma CLI commands based on your prompts. + +## Capabilities + +The [Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) enables support for VS Code agent mode. + +VS Code agent mode can perform the following tasks: + +- Check migration status (e.g. Flag unapplied migrations) +- Create and apply schema migrations automatically +- Sign in to the Prisma Data Platform +- Provision Prisma Postgres instances, letting you start coding right away + +## How to enable and use the VS Code agent + +The [latest version of the Prisma VS Code extension](https://marketplace.visualstudio.com/items?itemName=Prisma.prisma) fully supports agent mode. Since extensions update automatically, no manual action is required to enable it. + +:::note + +We recommend you to use the latest version of Prisma ORM. + +::: + +To use the agent mode: + +1. Open [GitHub Copilot Chat in VS Code and switch to **Agent** mode](https://code.visualstudio.com/docs/copilot/chat/chat-agent-mode#_use-agent-mode). +2. With GitHub Copilot Chat open and the Prisma extension updated, you can simply type a request such as: "Create a new database for me and add the connection string to the .env file". +3. The agent will request permission to make changes in your workspace. +4. It automatically handles login to your Prisma Data Platform account before proceeding. +5. Upon approval, the agent creates the new database and adds the connection string to your `.env` file. +6. You can also use agent mode to run migrations, generate the Prisma Client, and perform other tasks. + +:::note +Currently, the agent mode uses your default workspace in the Prisma Data Platform. +::: + +## Querying Prisma docs from VS Code using GitHub Copilot + +Complementing the agent, the Prisma Copilot extension allows you to query Prisma documentation directly within VS Code. + +You need to install the [Prisma for Copilot extension](https://github.com/apps/prisma-for-github-copilot) from the GitHub marketplace. + +Then, [switch to **Ask** mode in GitHub Copilot Chat](https://code.visualstudio.com/docs/copilot/chat/chat-ask-mode) and type your question using the `@prisma-for-github-copilot` namespace. + +For more details, refer to our [GitHub Copilot documentation](/orm/more/ai-tools/github-copilot). \ No newline at end of file diff --git a/content/250-postgres/300-database/550-local-development.mdx b/content/250-postgres/300-database/550-local-development.mdx new file mode 100644 index 0000000000..3e0a0f4ac1 --- /dev/null +++ b/content/250-postgres/300-database/550-local-development.mdx @@ -0,0 +1,137 @@ +--- +title: 'Local development' +metaTitle: 'Local development with Prisma Postgres (Early Access)' +metaDescription: 'Guide to setting up local development using Prisma Postgres (Early Access)' +tocDepth: 3 +toc: true +sidebar_class_name: early-access-badge +--- + + +[Prisma Postgres](/postgres) is our production-grade, cloud-native database and is ideal for staging and production environments. For rapid iteration and isolated testing, you can run a local Prisma Postgres instance (powered by [PG Lite](https://pglite.dev)). This guide shows you how to install and launch a local Prisma Postgres database. + +:::note + +Local Prisma Postgres is in [Early Access](/orm/more/releases#early-access) and is being actively developed. + +::: + +## Setting up local development for Prisma Postgres + +Follow these steps to set up local Prisma Postgres for development. + +:::note + +Please ensure you're running Node.js 20 or later, as it's required for local Prisma Postgres. + +::: + +### 1. Launching local Prisma Postgres + +Navigate into your project and start the local Prisma Postgres server using the following command: + +```terminal +npx prisma dev +``` + +This starts a local Prisma Postgres server that you can connect to using Prisma ORM. + +The output of the command contains a `DATABASE_URL` and looks like this: + +``` +Great Success! + +To connect to your local Prisma Postgres database via Prisma ORM, use the following connection string: + + DATABASE_URL="prisma+postgres://localhost:51213/?api_key=__API_KEY__" +``` + +Copy the `DATABASE_URL` and store it in your `.env` file. This will be used to connect to the local Prisma Postgres server: + +```bash file=.env +DATABASE_URL="prisma+postgres://localhost:51213/?api_key=__API_KEY__" +``` + +The `DATABASE_URL` is a connection string that Prisma uses to connect to the local Prisma Postgres server and is compatible with the [Prisma Postgres extension](https://www.npmjs.com/package/@prisma/extension-accelerate): + +```ts +import { withAccelerate } from '@prisma/extension-accelerate' + +const prisma = new PrismaClient().$extends(withAccelerate()) +``` + +This ensures no additional code changes are needed when switching from local Prisma Postgres to Prisma Postgres in production. + +Keep the local Prisma Postgres server running in the background while you work on your application. + +### 2. Applying migrations and seeding data + +Then in a separate terminal tab, run the `prisma migrate dev` command to create the database and run the migrations: + +```terminal +npx prisma migrate dev +``` + +:::note + +Make sure the local Prisma Postgres server is running before running the `prisma migrate dev` command. + +::: + +This will create the database and run the migrations. + +If you have a seeder script to seed the database, you should also run it in this step. + +:::note + +Currently, the local Prisma Postgres server does not persist data. This means that if you stop the server, all data will be lost. Hence have to run the migrations and seeds every time you start the server by using the `npx prisma dev` command. See the [limitation section below](#no-data-persistence-between-restarts). + +::: + +### 3. Running your application locally + +Start your application's development server. You can now perform queries against the local Prisma Postgres instance using Prisma ORM. + +To transition to production, you only need to update the database URL in the `.env` file with a Prisma Postgres connection url without additional application logic changes. + +## Known limitations + +### No data persistence between restarts + +Currently in the local Prisma Postgres server, data does not persist after server restart the server. Each time you restart the server (`npx prisma dev`), reapply migrations and seeds: + +```terminal +npx prisma migrate dev +npx prisma db seed +``` + +Persistent storage will be supported when local Prisma Postgres is [Generally Available](/orm/more/releases#generally-available-ga). + +### Caching is mocked locally + +[Prisma Postgres caching](/postgres/database/caching) is simulated locally. Queries always directly interact with the local Prisma Postgres instance, bypassing cache configurations: + +```typescript +const users = await prisma.user.findMany({ + cache: { ttl: 60 }, +}); +``` + +Caching works normally when you're using Prisma Postgres in staging and production. + +### Cache invalidation not supported locally + +[Cache invalidation (`$accelerate.invalidate()`)](/postgres/database/api-reference#accelerateinvalidate) is unsupported locally and throws an error. To safely handle this you can use a `try-catch` block: + +```typescript +try { + await prisma.$accelerate.invalidate(); +} catch (e) { + console.error(e); +} +``` + +### Prisma Postgres limitations apply to the local Prisma Postgres database + +All Prisma Postgres limitations also apply to local development for Prisma Postgres. Refer to the [Prisma Postgres limitations documentation](/postgres/more/known-limitations) for detailed information. +