agentleFS
cohen-lielcohen-liel/hivemind/.claude/skills/prisma-orm/SKILL.md

prisma-orm

Skill110 starsChanged 9 months agoApache-2.0View on GitHub

Prisma ORM patterns for Node.js/TypeScript backends. Use when defining Prisma schemas, writing queries, handling relations, migrations, or any database work in a Node.js/TypeScript project.

  • Reads credentials

1 other project uses a version of this.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

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

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 4

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Always use select to fetch only needed fields (never fetch passwords)

    line 152
  2. Very specific:

    Use include for relations instead of multiple queries (prevent N+1)

    line 153
  3. Very specific:

    Add @@index for all foreign keys and frequent filter columns

    line 156
  4. Very specific:

    Never use db.raw with user input — always use parameterized $queryRaw

    line 157

≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “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 ORM Patterns

Schema Design

// prisma/schema.prisma
generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  name      String
  password  String
  role      Role     @default(USER)
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  deletedAt DateTime? // Soft delete

  posts     Post[]
  sessions  Session[]

  @@index([email])
  @@map("users")  // Table name
}

enum Role {
  USER
  ADMIN
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String   @db.VarChar(255)
  body      String
  published Boolean  @default(false)
  authorId  Int
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  author    User     @relation(fields: [authorId], references: [id])
  tags      Tag[]    @relation("PostTags")

  @@index([authorId])
  @@index([published, createdAt(sort: Desc)])
}

model Tag {
  id    Int    @id @default(autoincrement())
  name  String @unique
  posts Post[] @relation("PostTags")
}

Client Setup

// lib/db.ts
import { PrismaClient } from '@prisma/client'

const globalForPrisma = global as unknown as { prisma: PrismaClient }

export const db = globalForPrisma.prisma ?? new PrismaClient({
  log: process.env.NODE_ENV === 'development' ? ['query', 'error'] : ['error'],
})

if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = db
// Single instance pattern prevents connection exhaustion in dev (Next.js HMR)

Query Patterns

// Find with relations (avoid N+1)
const posts = await db.post.findMany({
  where: { published: true, author: { deletedAt: null } },
  include: { author: { select: { id: true, name: true } }, tags: true },
  orderBy: { createdAt: 'desc' },
  take: 20,
  skip: (page - 1) * 20,
})

// Upsert
const setting = await db.setting.upsert({
  where: { userId_key: { userId, key } },
  create: { userId, key, value },
  update: { value },
})

// Transaction
const [user, post] = await db.$transaction([
  db.user.update({ where: { id: userId }, data: { postCount: { increment: 1 } } }),
  db.post.create({ data: { title, body, authorId: userId } }),
])

// Interactive transaction (for complex logic)
const result = await db.$transaction(async (tx) => {
  const user = await tx.user.findUniqueOrThrow({ where: { id: userId } })
  if (user.balance < amount) throw new Error('Insufficient balance')
  await tx.user.update({ where: { id: userId }, data: { balance: { decrement: amount } } })
  return tx.payment.create({ data: { userId, amount } })
})

// Raw SQL for complex queries
const stats = await db.$queryRaw<{ date: Date; count: bigint }[]>`
  SELECT date_trunc('day', created_at) as date, COUNT(*) as count
  FROM posts
  WHERE created_at > ${thirtyDaysAgo}
  GROUP BY 1 ORDER BY 1
`

Migrations

# Dev workflow
npx prisma migrate dev --name add_user_role      # Create + apply migration
npx prisma migrate dev --create-only             # Create only, don't apply
npx prisma db push                               # Push schema without migration (prototyping)
npx prisma studio                                # GUI to inspect DB

# Production
npx prisma migrate deploy                        # Apply pending migrations
npx prisma generate                              # Regenerate client after schema change

Soft Delete Pattern

// Middleware to filter soft-deleted records globally
db.$use(async (params, next) => {
  if (params.model === 'User') {
    if (params.action === 'findMany' || params.action === 'findFirst') {
      params.args.where = { ...params.args.where, deletedAt: null }
    }
    if (params.action === 'delete') {
      params.action = 'update'
      params.args.data = { deletedAt: new Date() }
    }
  }
  return next(params)
})

Rules

  • Always use select to fetch only needed fields (never fetch passwords)
  • Use include for relations instead of multiple queries (prevent N+1)
  • Transactions for multi-table writes (consistency guarantee)
  • findUniqueOrThrow / findFirstOrThrow to get automatic 404 behavior
  • Add @@index for all foreign keys and frequent filter columns
  • Never use db.raw with user input — always use parameterized $queryRaw
  • Single PrismaClient instance (global pattern above) for connection pooling

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.