Skip to content

Prisma + Postgres prompt

Rules that make your coding agent use Prisma ORM 7 with PostgreSQL as it ships today: prisma.config.ts, a driver adapter, lean queries, short transactions and migrations that deploy safely.

What it makes your agent good at

Agents trained on earlier Prisma versions put the URL in the schema, import from @prisma/client, build a client without an adapter, run db push against production and query inside loops. This prompt gives them Prisma 7 as installed, from prisma.config.ts and the prisma-client generator to schema design, cursor pagination, interactive transactions, typed raw SQL and a migration workflow you can deploy.

  1. Prisma 7 setup, not Prisma 5prisma.config.ts for the URL, the prisma-client generator with an output path, and a PrismaPg adapter on the client.
  2. One client per processA globalThis cache in development, pool size set on the adapter, and never a client per request.
  3. Schemas that hold upuuid(7) ids, @updatedAt, indexed foreign keys, compound uniques and enums, money in cents or Decimal.
  4. Lean, safe queriesOnly the fields needed, relations in one query, cursor pagination, atomic updates and mapped P2002 errors.
  5. Transactions and raw SQLShort interactive transactions on tx, tagged $queryRaw, and TypedSQL for typed raw queries.
  6. Migrations you can deploymigrate dev with reviewed SQL, migrate deploy in production, changes in steps, and never db push on shared data.

The Prisma + Postgres rules

137 lines, current to Prisma ORM 7.10 with PostgreSQL and Next.js 16.4. Last reviewed October 23, 2026. Plain Markdown, no front matter: each agent's is below.

Download

prisma-postgres.md

# Prisma + Postgres

You are working in a TypeScript project (often Next.js 16) that uses Prisma ORM 7 with PostgreSQL. Write code for the versions in `package.json`: Prisma 7 moved the connection URL out of the schema, generates the client into your project, requires a driver adapter and dropped several APIs you may remember.

## Before you write code

- Check `package.json` for `prisma`, `@prisma/client` and `@prisma/adapter-pg` (all 7.x, same version), and the scripts that run `prisma generate` and migrations.
- Read `prisma.config.ts` (schema path, datasource URL, migrations path and seed command) and the schema (`prisma/schema.prisma` or a `prisma/` folder of `.prisma` files) before writing a query.
- Find where the client is created (`lib/db.ts`, `lib/prisma.ts`) and import it from there. Find the generator's `output`: the client is imported from that folder, not from `@prisma/client`.
- Read `prisma/migrations/` to see how the schema got here, and the generated model types (`<output>/models/`) when unsure of a field.

## Config, generator and client

```ts
// prisma.config.ts
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") },
});
```

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

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

- The CLI's connection lives in `prisma.config.ts`, never as `url = env(...)` in the schema. Prisma 7 does not load `.env` for you: load it in the config (`dotenv/config`) or through your runtime.
- `datasource.url` is what migrations use: a direct connection, not a transaction-mode pooler. The app connects through the adapter, which may use a pooled URL.
- Use the `prisma-client` generator with an `output` path. Git-ignore the output and run `prisma generate` in `postinstall` or the build, and again after every schema change: `migrate dev` no longer runs it.

```ts
// lib/db.ts
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "@/generated/prisma/client";

const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };

export const prisma =
  globalForPrisma.prisma ??
  new PrismaClient({
    adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
  });

if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
```

- One client per process. The `globalThis` cache stops hot reload from opening a new pool on every edit. Never create a client per request or inside a component.
- A driver adapter is required (or `accelerateUrl` for Accelerate). The constructor has no `datasources` or `datasourceUrl` option. Pool size and timeouts are `pg` options passed to `PrismaPg` (`max`, `connectionTimeoutMillis`); on serverless, keep `max` small and connect through a pooler.
- Import types and enums from `<output>/client` on the server, and from `<output>/browser` in code that may reach the browser; it has no `PrismaClient`.
- `$use` middleware is gone: use `$extends` (query extensions, computed fields) and keep extensions on the one shared client. Hide sensitive columns everywhere with the constructor's `omit` option.

## Schema design

- IDs: `String @id @default(uuid(7)) @db.Uuid` (time-ordered) or `cuid(2)`; an `Int @id @default(autoincrement())` only when IDs never leave the database.
- Every table gets `createdAt DateTime @default(now())` and `updatedAt DateTime @updatedAt`.
- Relations: name both sides, set `onDelete` (`Cascade` for owned rows, `Restrict` or `SetNull` otherwise), and add `@@index([authorId])` on every foreign key: Postgres does not index them for you.
- Use `@unique` and compound `@@unique([orgId, slug])` for real invariants and rely on the error (`P2002`) rather than checking first. Add `@@index` for the columns you filter and sort by, in that order.
- Use `enum` for closed sets of states. Store money as integer cents or `Decimal @db.Decimal(12, 2)`, never `Float`.
- Map to snake_case names with `@map` and `@@map` when the database already uses them; keep model and field names camelCase in code.

## Queries

- `select` only the fields the caller needs, especially for lists and anything sent to a client. Define reusable shapes with `satisfies Prisma.UserSelect` and type results with `Prisma.UserGetPayload<{ select: typeof userCard }>`.
- Avoid N+1: fetch relations in the same query with `select`/`include`, or batch with `where: { id: { in: ids } }`. Never `await` a query inside a loop over rows.
- Paginate with cursors for feeds and large tables:

```ts
const page = await prisma.post.findMany({
  where: { published: true },
  orderBy: [{ createdAt: "desc" }, { id: "desc" }],
  take: 20,
  ...(cursor ? { cursor: { id: cursor }, skip: 1 } : {}),
  select: { id: true, title: true, createdAt: true },
});
```

  Order by a unique column last so pages never repeat or skip rows. Offset (`skip`) is fine only for small, bounded page counts.
- Use atomic updates (`{ increment: 1 }`, `updateMany` with a `where` that encodes the precondition) instead of read-modify-write.
- `findUnique` returns `null`; `findUniqueOrThrow` throws `P2025`. Catch `Prisma.PrismaClientKnownRequestError` (`Prisma` from `<output>/client`) and map `P2002` (unique), `P2003` (foreign key) and `P2025` (not found) to user-facing results.

## Transactions and raw SQL

- Nested writes are already one transaction. For independent writes that must succeed together, `prisma.$transaction([a, b])`.
- For logic between queries, use an interactive transaction and only `tx` inside it:

```ts
await prisma.$transaction(
  async (tx) => {
    const from = await tx.account.update({ where: { id: fromId }, data: { balance: { decrement: amount } } });
    if (from.balance < 0) throw new Error("Insufficient funds"); // rolls back
    await tx.account.update({ where: { id: toId }, data: { balance: { increment: amount } } });
  },
  { isolationLevel: Prisma.TransactionIsolationLevel.Serializable, timeout: 10_000 }
);
```

  Keep it short: no HTTP calls, emails or file uploads inside, since it holds a connection and locks. Retry serialization failures (`P2034`).
- Raw SQL only through tagged templates, which parameterize values: ``prisma.$queryRaw<Row[]>`SELECT … WHERE id = ${id}` ``, `$executeRaw` for writes, `Prisma.sql` and `Prisma.join` to compose. Never `$queryRawUnsafe` or `$executeRawUnsafe` with interpolated input.
- For typed raw queries, use TypedSQL (still a preview feature): `previewFeatures = ["typedSql"]` in the generator, one query per file in `prisma/sql/*.sql`, `prisma generate --sql`, then `prisma.$queryRawTyped(getActiveUsers(minAge))` with the function imported from `<output>/sql`.

## Migrations and seeding

- Development: edit the schema, run `prisma migrate dev --name <change>`, read the generated SQL, commit `prisma/migrations/` with the schema change. Use `--create-only` to edit the SQL first: renames (Prisma drops and re-adds a renamed column), defaults and backfills for new required columns.
- Production and CI: `prisma migrate deploy`, before the new code serves traffic. Never `migrate dev`, `migrate reset` or `db push` against a shared or production database; `db push` is for throwaway prototypes.
- Make breaking changes in steps (add column, backfill, switch code, then drop) so old and new code both work during a deploy.
- Never edit a migration that has been applied anywhere; add a new one.
- Seed with the command in `prisma.config.ts` (`migrations.seed`), run explicitly with `prisma db seed`; migrations do not seed. Write seeds with `upsert` so they can run twice, and give scripts their own client.

## Server-only data access

- Query only from server code: Server Components, Server Functions, Route Handlers and a data layer marked `import "server-only"`. Never import the client into a Client Component or a file it imports.
- Authorize before querying, and scope by the caller's identity in the `where` (`{ id, ownerId: user.id }`), not after loading the row.
- Return plain data across the server-client boundary: `select` the fields, and convert `Decimal` and `BigInt` (`.toString()`, `Number()`) before passing them to Client Components.
- Validate input (Zod) before it reaches `where` or `data`; never spread request bodies into `data`.

## Do not

- Do not put `url` in the schema's datasource, import `PrismaClient` from `@prisma/client` when the project uses the `prisma-client` generator, or construct a client without an adapter.
- Do not use `$use`, `datasources`, `rejectOnNotFound` or `$queryRawUnsafe` with user input.
- Do not run `db push` or `migrate reset` on production, or hand-edit applied migrations.
- Do not create a client per request, query in loops, or `include` whole relations when a few fields will do.

## Before you finish

- Run `prisma validate` and `prisma format`, then `prisma generate`, then the type checker.
- After a schema change, run `prisma migrate dev --name <change>`, read the SQL for drops or table rewrites, and run `prisma migrate status`.
- Check new queries for an index on every column they filter or sort by, and list any migration that locks or rewrites a large table for the reviewer.

9,326 characters, 1,383 words. Under Windsurf's 12,000-character limit for a rule, as every prompt here is.

Use it in your agent

The same rules, where your agent reads them. Each file has the front matter its agent needs, set to apply on every request.

Claude Code

A rule it loads every session

  1. Save it as .claude/rules/prisma-postgres.md in your project, front matter included, or run the install command.
  2. Claude Code loads every file in .claude/rules with your CLAUDE.md when a session starts.
  3. Prefer one file? Paste it into CLAUDE.md under its own heading instead.

.claude/rules/prisma-postgres.md

# Prisma + PostgresYou are working in a TypeScript project (often Next.js 16) that uses Prisma ORM 7 with PostgreSQL. Write code for the versions in `package.json`: Prisma 7 moved the connection URL out of the schema, generates the client into your project, requires a driver adapter and dropped several APIs you may remember.## Before you write code- Check `package.json` for `prisma`, `@prisma/client` and `@prisma/adapter-pg` (all 7.x, same version), and the scripts that run `prisma generate` and migrations.- Read `prisma.config.ts` (schema path, datasource URL, migrations path and seed command) and the schema (`prisma/schema.prisma` or a `prisma/` folder of `.prisma` files) before writing a query.- Find where the client is created (`lib/db.ts`, `lib/prisma.ts`) and import it from there. Find the generator's `output`: the client is imported from that folder, not from `@prisma/client`.- Read `prisma/migrations/` to see how the schema got here, and the generated model types (`<output>/models/`) when unsure of a field.## Config, generator and client…

Or let the shadcn CLI write this file: sign in (free) for your command.

Cursor

A project rule with front matter

  1. Save it as .cursor/rules/prisma-postgres.mdc, front matter included, or run the install command.
  2. alwaysApply: true adds it to every Agent request in this project.
  3. Check it under Cursor Settings, Rules, then commit the folder for your team.

.cursor/rules/prisma-postgres.mdc

---description: "Prisma ORM 7 with PostgreSQL: config, client setup, schema design, queries, transactions, raw SQL, migrations and seeding."alwaysApply: true---# Prisma + PostgresYou are working in a TypeScript project (often Next.js 16) that uses Prisma ORM 7 with PostgreSQL. Write code for the versions in `package.json`: Prisma 7 moved the connection URL out of the schema, generates the client into your project, requires a driver adapter and dropped several APIs you may remember.## Before you write code- Check `package.json` for `prisma`, `@prisma/client` and `@prisma/adapter-pg` (all 7.x, same version), and the scripts that run `prisma generate` and migrations.- Read `prisma.config.ts` (schema path, datasource URL, migrations path and seed command) and the schema (`prisma/schema.prisma` or a `prisma/` folder of `.prisma` files) before writing a query.- Find where the client is created (`lib/db.ts`, `lib/prisma.ts`) and import it from there. Find the generator's `output`: the client is imported from that folder, not from `@prisma/client`.- Read `prisma/migrations/` to see how the schema got here, and the generated model types (`<output>/models/`) when unsure of a field.## Config, generator and client…

Or let the shadcn CLI write this file: sign in (free) for your command.

Windsurf

A workspace rule for Cascade

  1. Save it as .windsurf/rules/prisma-postgres.md, or run the install command.
  2. trigger: always_on applies it to every Cascade request in this workspace.
  3. Windsurf reads up to 12,000 characters per rule; this one is 9,326.

.windsurf/rules/prisma-postgres.md

---trigger: always_on---# Prisma + PostgresYou are working in a TypeScript project (often Next.js 16) that uses Prisma ORM 7 with PostgreSQL. Write code for the versions in `package.json`: Prisma 7 moved the connection URL out of the schema, generates the client into your project, requires a driver adapter and dropped several APIs you may remember.## Before you write code- Check `package.json` for `prisma`, `@prisma/client` and `@prisma/adapter-pg` (all 7.x, same version), and the scripts that run `prisma generate` and migrations.- Read `prisma.config.ts` (schema path, datasource URL, migrations path and seed command) and the schema (`prisma/schema.prisma` or a `prisma/` folder of `.prisma` files) before writing a query.- Find where the client is created (`lib/db.ts`, `lib/prisma.ts`) and import it from there. Find the generator's `output`: the client is imported from that folder, not from `@prisma/client`.- Read `prisma/migrations/` to see how the schema got here, and the generated model types (`<output>/models/`) when unsure of a field.## Config, generator and client…

Or let the shadcn CLI write this file: sign in (free) for your command.

GitHub Copilot

Instructions for the repository

  1. Save it as .github/instructions/prisma-postgres.instructions.md, or run the install command.
  2. applyTo: "**" applies it to every request in this repository.
  3. Or paste it into .github/copilot-instructions.md, which Copilot reads for every request.

.github/instructions/prisma-postgres.instructions.md

---description: "Prisma ORM 7 with PostgreSQL: config, client setup, schema design, queries, transactions, raw SQL, migrations and seeding."applyTo: "**"---# Prisma + PostgresYou are working in a TypeScript project (often Next.js 16) that uses Prisma ORM 7 with PostgreSQL. Write code for the versions in `package.json`: Prisma 7 moved the connection URL out of the schema, generates the client into your project, requires a driver adapter and dropped several APIs you may remember.## Before you write code- Check `package.json` for `prisma`, `@prisma/client` and `@prisma/adapter-pg` (all 7.x, same version), and the scripts that run `prisma generate` and migrations.- Read `prisma.config.ts` (schema path, datasource URL, migrations path and seed command) and the schema (`prisma/schema.prisma` or a `prisma/` folder of `.prisma` files) before writing a query.- Find where the client is created (`lib/db.ts`, `lib/prisma.ts`) and import it from there. Find the generator's `output`: the client is imported from that folder, not from `@prisma/client`.- Read `prisma/migrations/` to see how the schema got here, and the generated model types (`<output>/models/`) when unsure of a field.## Config, generator and client…

Or let the shadcn CLI write this file: sign in (free) for your command.

Codex & AGENTS.md

The file most agents read

  1. Paste it into AGENTS.md at your project's root, under its own heading.
  2. Codex reads AGENTS.md before it starts work, and so do Cursor, Zed, Jules, Amp and Copilot's coding agent.
  3. A folder can have its own AGENTS.md: the one closest to the file being edited wins.

AGENTS.md

## Prisma + PostgresYou are working in a TypeScript project (often Next.js 16) that uses Prisma ORM 7 with PostgreSQL. Write code for the versions in `package.json`: Prisma 7 moved the connection URL out of the schema, generates the client into your project, requires a driver adapter and dropped several APIs you may remember.### Before you write code- Check `package.json` for `prisma`, `@prisma/client` and `@prisma/adapter-pg` (all 7.x, same version), and the scripts that run `prisma generate` and migrations.- Read `prisma.config.ts` (schema path, datasource URL, migrations path and seed command) and the schema (`prisma/schema.prisma` or a `prisma/` folder of `.prisma` files) before writing a query.- Find where the client is created (`lib/db.ts`, `lib/prisma.ts`) and import it from there. Find the generator's `output`: the client is imported from that folder, not from `@prisma/client`.- Read `prisma/migrations/` to see how the schema got here, and the generated model types (`<output>/models/`) when unsure of a field.### Config, generator and client…

AGENTS.md is shared with your own instructions, so paste the rules in: the copy sets their headings a level down.

Rules teach it. The MCP equips it. With Pro, your agent installs every component, block and icon it needs, from a prompt.

Get Pro

Pricing

Give your agent the parts, with Pro

The prompts are free. Every Pro plan adds the MCP server, so your agent installs the components, blocks and icons it writes code around.

4.9/5 out of 5 · 150+ reviewsfrom 150+ founders and developers.

Billed once a year in USD. Cancel anytime.

Individual

For personal projects & open source

$32instead of $49/mo

$389 billed yearly

  • How many people can use the license.Seats: 1 seat
  • Client work, SaaS products and anything you charge for.Commercial use: Personal & open source only
  • Page sections in 56 categories, from heroes and pricing tables to dashboards and settings, on every framework and UI library, in your theme.Blocks: All 6,181 blocks
  • Complete Next.js sites for startups, SaaS, agencies and portfolios, every page designed, ready to ship.Templates: All 14 templates
  • Your AI agent searches, previews and installs any component, block, icon or DESIGN.md from a prompt: 22 tools in Claude Code, Cursor, VS Code and 35 more clients.MCP server: 38 AI clients
  • Buttons with motion and states of their own, from an arrow that slides in to a burst of confetti.Animated buttons: All 35 buttons
  • Typewriters, scrambles, counters and more, for headlines, labels and numbers.Text effects: All 97 effects
  • Animated backgrounds for heroes, sections and cards, from a soft aurora to a flock that flees the cursor. Most are pure CSS.Backgrounds: All 100 backgrounds
  • WebGPU shaders, from a slow aurora to a black hole, each drawing only while it's on screen.Shaders: All 100 shaders
  • One design and one theme on all four: the components, blocks and effects are built for each framework.Frameworks: React, Vue, Svelte, Solid
  • React on Base UI, Radix UI, React Aria or Ark UI: install the version for the library your project already uses. Vue, Svelte and Solid run on Ark UI.UI libraries: Base UI, Radix, Aria, Ark
  • From a button to a date picker, a color picker or a guided tour: accessible, typed in TypeScript, each with live demos.Components: All 174 components
  • Real-world patterns built from the components, in 53 galleries: forms, tables, menus, dialogs and more.Examples: All 1,103 examples
  • Area, bar, line, pie, radar and radial charts on TanStack Charts, on every framework. React also gets the Recharts originals.Charts: All 70 charts
  • Debounce, local storage, media queries and more: each hook is one typed file you own.React hooks: All 35 hooks
  • From 222 libraries, Lucide, Heroicons, Tabler and Material Symbols among them, as SVG or a React component in one command.Icons: 294k+ icons
  • Stripe, Linear, Apple and 497 more: a brand's colors, typography and components in one file your AI agent builds from.DESIGN.md files: All 500 brands
  • Restyle every component and block at once: 8 styles, 7 grays, 18 colors and 5 radii, shared as a shadcn preset code.Theme builder: 8 styles × 18 colors
  • Priority requests are answered first.Support: Standard

Team

Most popular

For freelancers, agencies & startups

$66instead of $99/mo

$789 billed yearly · ≈ $13/dev/mo

Everything in Individual, plus

  • How many people can use the license.Seats: Up to 5 seats
  • Client work, SaaS products and anything you charge for.Commercial use: Included
  • Priority requests are answered first.Support: Priority

Organization

For companies with larger teams

$132instead of $199/mo

$1,589 billed yearly

Everything in Team, plus

  • How many people can use the license.Seats: Unlimited seats
  • Secure checkout via Stripe
  • Code lives in your repo
  • Keep what you've shipped if you cancel
  • License terms

Prisma + Postgres prompt FAQ

What the Prisma + Postgres prompt covers and how to use it in your agent.

When does the Prisma + Postgres prompt use migrate dev, migrate deploy or db push?

migrate dev in development, where it creates a migration from the schema change for you to read and commit. migrate deploy in CI and production, before the new code serves traffic. db push only for throwaway prototypes, never against a shared or production database.

How does the Prisma + Postgres prompt handle column renames?

Prisma reads a renamed field as a dropped column and a new one, which loses data. The prompt has the agent create the migration with --create-only, change the SQL to a rename, and ship breaking changes in steps so old and new code both work during a deploy.

How does the Prisma + Postgres prompt seed the database?

With the seed command set in prisma.config.ts and run explicitly with prisma db seed, since migrations no longer seed in Prisma 7. Seeds use upsert so they can run twice, and scripts create their own client instead of importing the app's server-only modules.

4.9 out of 5 from 150+ developers

Rules teach it. The MCP equips it.

Every component, block and icon, installed by your AI agent on your stack. The prompts stay free.

Get Pro
  • Cancel anytime
  • Keep what you've shipped