AI Skill Library

Prisma ORM

Schema definition, migrations, queries, relations, transactions, raw SQL.

prismadatabaseormtypescript
# Prisma ORM

## Schema (schema.prisma)
```prisma
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}
generator client {
  provider = "prisma-client-js"
}
model User {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  name      String?
  createdAt DateTime @default(now())
  posts     Post[]
}
model Post {
  id       Int     @id @default(autoincrement())
  title    String
  author   User    @relation(fields: [authorId], references: [id])
  authorId Int
}
```

## Migrations
```bash
npx prisma migrate dev --name add_user   # dev
npx prisma migrate deploy                # prod (CI)
npx prisma db push                       # prototype (no migration)
npx prisma studio                        # GUI browser
```

## Queries
```ts
const user = await prisma.user.findUnique({ where: { email: 'a@b.c' } })
const users = await prisma.user.findMany({
  where: { posts: { some: { published: true } } },
  include: { posts: true },
  orderBy: { createdAt: 'desc' },
  take: 10, skip: 20,
})
await prisma.user.create({ data: { email: 'x@y.z' } })
await prisma.user.update({ where: { id: 1 }, data: { name: 'Bob' } })
await prisma.user.delete({ where: { id: 1 } })
```

## Transactions
```ts
await prisma.$transaction(async (tx) => {
  const u = await tx.user.create({ data: { email: 'a@b.c' } })
  await tx.post.create({ data: { title: 'Hi', authorId: u.id } })
})
```

## Raw SQL
```ts
const result = await prisma.$queryRawUnsafe('SELECT * FROM users WHERE id = $1', userId)
await prisma.$executeRawUnsafe('UPDATE users SET name = $1 WHERE id = $2', name, id)
```

API: /api/skills/prisma-orm