# Patroon: Prisma Client singleton

## lib/prisma.ts

PostgreSQL via `pg` + `@prisma/adapter-pg` (Neon/Vercel).

```ts
import { PrismaClient } from '@prisma/client'
import { Pool } from 'pg'
import { PrismaPg } from '@prisma/adapter-pg'

function createPrismaClient() {
  const url = process.env.DATABASE_URL
  if (!url) throw new Error('DATABASE_URL is not set')

  const pool = new Pool({ connectionString: url })
  const adapter = new PrismaPg(pool)
  return new PrismaClient({
    adapter,
    log: process.env.NODE_ENV === 'development' ? ['error', 'warn'] : ['error'],
  })
}

const globalForPrisma = globalThis as unknown as { prisma: PrismaClient | undefined }

export const prisma = globalForPrisma.prisma ?? createPrismaClient()

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

## prisma.config.ts (Prisma v7 vereiste)

```ts
import 'dotenv/config'
import { defineConfig } from 'prisma/config'

export default defineConfig({
  schema: 'prisma/schema.prisma',
  migrations: { path: 'prisma/migrations' },
})
```

## Prisma generators

`prisma/schema.prisma` bevat twee generators:

```prisma
generator client {
  provider = "prisma-client-js"
}

generator erd {
  provider = "prisma-erd-generator"
  output   = "../docs/erd.svg"
}
```

`prisma generate` bouwt dus twee artifacts:

- Prisma Client in `node_modules/@prisma/client`
- het ERD-diagram in `docs/erd.svg`

Gebruik volledige `prisma generate` alleen lokaal. De ERD-generator gebruikt Mermaid/Puppeteer en mag niet in CI of Vercel draaien.

## Commands

| Command | Gebruik |
|---|---|
| `npx prisma db push` | Schema synchroniseren naar de database |
| `npx prisma db seed` | Seeddata laden |
| `npx prisma generate --generator client` | Alleen Prisma Client genereren; gebruiken in CI/deployment |
| `npm run db:erd` | `prisma generate`: Prisma Client en `docs/erd.svg` genereren |
| `npm run db:erd:watch` | `prisma/schema.prisma` watchen en ERD opnieuw genereren |
| `npm run dev` | Next.js dev server plus ERD watcher starten |

Belangrijk: `db push` schrijft naar de database, maar genereert geen ERD. Gebruik na schemawijzigingen lokaal `npm run db:erd` of laat `npm run dev` de watcher draaien. Gebruik in CI en deployment alleen `npx prisma generate --generator client`.
