agentleFS
manishdashsharmamanishdashsharma/express-backend-skills/skills/prisma-postgres/SKILL.md

prisma-postgres

Skill0 starsChanged 15 days agoMITView on GitHub

PostgreSQL with Prisma 7 done right — read/write client getters with replica support, schema requirements and indexes, explicit select, pagination, N+1-free batching, transactions with atomic counters, error codes, migrations workflow and raw SQL rules. Use when writing or reviewing Prisma schema, queries, migrations or Postgres data access in Node.js.

13 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use prisma-mongodb-upgrade, prisma-driver-adapter-implementation and 4 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • nateruzeSkill

    prisma-mongodb-upgrade

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

    Also in 7 projects that use this

  • adrianhajdinSkill

    prisma-driver-adapter-implementation

    Required reference for Prisma v7 driver adapter work. Use when implementing or modifying adapters, adding database drivers, or touching SqlDriverAdapter/Transaction interfaces. Contains critical contract details not inferable from code examples — including the transaction lifecycle protocol, error mapping requirements, and verification checklist. Existing implementations do not replace this skill.

    Also in 9 projects that use this

  • adrianhajdinSkill

    prisma-postgres-setup

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

    Also in 8 projects that use this

  • nateruzeSkill

    prisma-compute

    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`, `auth workspace`, Compute apps/deployments/build logs/domains, `@prisma/cli agent install`, `@prisma/cli feedback`, 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.

    Also in 6 projects that use this

  • liveblocksSkill

    liveblocks-best-practices

    Use this skill when building, debugging, or answering questions

    Also in 3 projects that use this

  • mftsSkill

    trigger-cost-savings

    Analyze Trigger.dev tasks, schedules, and runs for cost optimization opportunities. Use when asked to reduce spend, optimize costs, audit usage, right-size machines, or review task efficiency. Requires Trigger.dev MCP tools for run analysis.

    Also in 3 projects that use this

The file

We split this skill into the rules it gives an agent

9 rules. 0 are common, 4 are distinctive, and 5 are very specific to this project.

  • 0

    Common

    Most of the 11 edited versions we read keep these.

  • 4

    Distinctive

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  • could be automatic: a setting could enforce it
  1. Very specific:

    Never new PrismaClient() in a module.

    line 10
  2. Distinctive:

    Call the getter inside the function, never at module top level.

    line 16
  3. Very specific:

    Every table: isActive Boolean @default(true), createdAt, updatedAt, a scope field.

    line 46
  4. Very specific:

    Always select or include explicitly: Never return a full row; never include a relation without its own select.

    line 69
  5. Distinctive:

    Use an interactive transaction when several writes must succeed together:

    line 79
  6. Distinctive:

    Keep transactions short: no network calls, no AI calls, no email inside.

    line 97
  7. Distinctive:

    Do not catch Prisma errors in services just to rethrow them.

    line 111
  8. Very specific:

    After a schema change: npm run db:generate && npm run db:migrate -- --name <what_changed>.

    line 115
  9. Very specific:

    Only when Prisma has no equivalent (full-text, vector search, window functions).

    line 123

“Common” is measured: kept by at least 6 in 10 of the 11 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Prisma / PostgreSQL

Client access

Never new PrismaClient() in a module. Use the getters:

import { getWriteDB, getReadDB } from '../../../config/databases.js';
  • Call the getter inside the function, never at module top level.
  • getReadDB() for reads (uses the read replica when DATABASE_READ_URL is set).
  • getWriteDB() for writes and for read-before-write consistency checks (a replica may lag).
  • Prisma 7 uses the driver adapter: new PrismaClient({ adapter: new PrismaPg({ connectionString, max }) }). Pool size comes from config.

Schema requirements

model Invoice {
  id         String        @id @default(cuid())
  orgId      String
  customerId String
  number     Int
  status     InvoiceStatus @default(DRAFT)
  total      Decimal       @db.Decimal(12, 2)
  isActive   Boolean       @default(true)
  createdAt  DateTime      @default(now())
  updatedAt  DateTime      @updatedAt

  org      Organization @relation(fields: [orgId], references: [id])
  customer Customer     @relation(fields: [customerId], references: [id])

  @@unique([orgId, number])
  @@index([orgId, isActive])
  @@index([orgId, isActive, status, createdAt])
  @@index([customerId])
  @@map("invoices")
}
  • Every table: isActive Boolean @default(true), createdAt, updatedAt, a scope field.
  • @@index([scope, isActive]) always. Every field in a where or orderBy is covered by an index. Foreign keys get their own index (Postgres does not add one).
  • @@map to snake_case plural table names; be consistent with @map on columns.
  • Money is Decimal, never Float. Status fields are Prisma enums.
  • Append-only tables (audit logs, billing events) may skip isActive — say so explicitly.

Query rules

const db = getReadDB();
const where = { orgId, isActive: true, ...(status ? { status } : {}) };
const [total, items] = await Promise.all([
  db.invoice.count({ where }),
  db.invoice.findMany({
    where,
    select: { id: true, number: true, status: true, total: true, createdAt: true },
    orderBy: { createdAt: 'desc' },
    skip: (page - 1) * limit,
    take: limit,
  }),
]);
  • Always select or include explicitly. Never return a full row; never include a relation without its own select.
  • Always isActive: true + scope in where. Use findFirst with scope rather than findUnique by id alone, so another tenant's id returns nothing.
  • No query inside a loop. Batch with where: { id: { in: ids } } and join in memory with a Map, or use a nested select.
  • Independent queries in Promise.all.
  • Scoped writes: updateMany({ where: { id, orgId, isActive: true }, data }) and check count === 0 → 404. This avoids a separate existence read and cannot touch another tenant's row.
  • Soft delete: data: { isActive: false }. Never delete / deleteMany.
  • Bulk: createMany, updateMany. Never a loop of single writes.

Transactions

Use an interactive transaction when several writes must succeed together:

const invoice = await getWriteDB().$transaction(async (tx) => {
  const org = await tx.organization.update({
    where: { id: orgId },
    data: { invoiceSeq: { increment: 1 } },
    select: { invoiceSeq: true },
  });
  return tx.invoice.create({
    data: { orgId, customerId, number: org.invoiceSeq, total },
    select: { id: true, number: true },
  });
});
  • Sequence/counter fields are bumped with { increment: 1 } inside the same transaction as the insert. Never read-then-write a counter.
  • Audit rows are written in the same transaction as the change they describe.
  • Keep transactions short: no network calls, no AI calls, no email inside.
  • Derived totals that are read often are maintained in the same transaction as the change, not recomputed with a live SUM() on every read.

Errors

Handled centrally by publicError; throw your own only for a domain-specific sentence:

CodeMeaningStatus
P2002Unique constraint409
P2025Record not found404
P2003Foreign key violation409
P2000Value too long400

Do not catch Prisma errors in services just to rethrow them.

Migrations

  • After a schema change: npm run db:generate && npm run db:migrate -- --name <what_changed>.
  • Migrations are committed. Never edit an applied migration; write a new one.
  • Deploy runs prisma migrate deploy (entrypoint or release step), never migrate dev.
  • Destructive changes go in two steps: stop reading/writing the column, deploy, then drop it in a later migration.
  • Backfills that touch many rows are a migration SQL step or a one-off job script, not request-time code.

Raw SQL

Only when Prisma has no equivalent (full-text, vector search, window functions). Always the tagged template $queryRaw\... ${value}`so values are parameterized. Never$queryRawUnsafe` with user input.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.