# Prisma

Prisma is a TypeScript ORM with auto-generated client and migrations. This guide covers using Prisma with Specific.

## Setup

Pass the database URL to your service and always add a `pre_deploy` step to run database migrations.

```hcl
build "api" {
  base = "node"
  command = "npx prisma generate && npm run build"
}

service "api" {
  build = build.api
  command = "node dist/index.js"

  endpoint {
    public = true
  }

  env = {
    PORT = port
    DATABASE_URL = postgres.main.url
  }

  pre_deploy {
    command = "npx prisma migrate deploy"
  }

  dev {
    command = "npm run dev"
  }
}

postgres "main" {}
```

Note: The build command includes `prisma generate` to ensure the Prisma client is generated before building.

## Prisma schema

Configure the datasource in `prisma/schema.prisma`:

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

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

## Development

Use `specific exec` to run migrations:

```bash
# Create and apply a new migration
specific exec api -- npx prisma migrate dev --name add_users_table

# Apply pending migrations
specific exec api -- npx prisma migrate dev

# Push schema directly (for rapid prototyping)
specific exec api -- npx prisma db push
```

To seed your database, add a seed script to `package.json`:

```json
{
  "prisma": {
    "seed": "npx tsx prisma/seed.ts"
  }
}
```

Then run it:

```bash
specific exec api -- npx prisma db seed
```

## Database client

Create a singleton Prisma client:

```typescript
import { PrismaClient } from "@prisma/client";

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

export const prisma = globalForPrisma.prisma ?? new PrismaClient();

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

The singleton pattern prevents multiple client instances during hot reloading in development.

## Prisma Studio

Prisma Studio is not necessary as `specific dev` includes a database viewer and editor in its admin interface.
