본문 바로가기

11월 26일 21:02 기준 · 10분마다 새 소식을 확인합니다

광고나 제휴로 순서를 바꾸지 않습니다 · pick 기준 보기 ›
소식 받기
코딩 · 개발

Prisma ORM 설계 규칙 설정

AI 코딩 어시스턴트에 Prisma ORM DB 모범 사례 가이드라인을 주입하여 높은 품질의 DB 코드를 유도합니다.

추천 툴
CursorAI 분류
쓰인 기법
역할 부여 · 규칙 명시 · 신뢰도 측정

프롬프트 원문

Cursor로 실행
# Prisma ORM taste of a type-safe database pragmatist
- Treat `schema.prisma` as the source of truth for models, and generate the client in CI so `node_modules/.prisma` never drifts. Confidence: 0.95
- Prefer one Prisma schema per deployable service; split only when bounded contexts truly own separate databases. Confidence: 0.85
- Name models in PascalCase singular (`User`, `OrderItem`) and map table names explicitly when the database already exists. Confidence: 0.80
- Use `@id` with `cuid()` or `uuid()` for public IDs, and keep autoincrement integers for internal-only keys when you must. Confidence: 0.75
- Declare every relation with both sides and an explicit `onDelete` / `onUpdate` so cascade behavior is never accidental. Confidence: 0.90
- Add `@@index` and `@@unique` in the schema for every query pattern you rely on, and verify with `EXPLAIN` in staging. Confidence: 0.85
- Ship schema changes as Prisma Migrate migrations checked into git; never use `db push` against production. Confidence: 0.95
- Review generated SQL in each migration file before merging, especially drops, renames and type changes. Confidence: 0.90
- Keep migrations backward compatible across a rolling deploy: add columns nullable first, backfill, then tighten. Confidence: 0.85
- Use `prisma generate` in the Docker build and in postinstall only when the schema changed; avoid surprising local regenerations. Confidence: 0.75
- Prefer `findMany` with `select` or `include` that lists only needed fields; never return full rows to the API by default. Confidence: 0.85
- Wrap multi-step writes in `prisma.$transaction`, and keep transactions short with no external HTTP inside them. Confidence: 0.90
- Use interactive transactions sparingly; for simple batches prefer the array form of `$transaction`. Confidence: 0.80
- Put database access behind a small repository or data module, not sprinkled through React Server Components and route handlers. Confidence: 0.80
- Seed with `prisma db seed` using idempotent upserts so preview environments can rebuild safely. Confidence: 0.80
- Enable query logging in development and slow-query logging in production; treat N+1 patterns as bugs. Confidence: 0.85
- Use Prisma's typed `Prisma.XxxGetPayload` helpers for shared query shapes instead of hand-rolled interfaces that drift. Confidence: 0.80
- Pin the Prisma CLI and engine versions together, and upgrade them in a dedicated PR after reading the release notes. Confidence: 0.85
- For raw SQL, use `Prisma.sql` tagged templates only, never string concatenation with user input. Confidence: 0.95
- Run `prisma migrate diff` in CI against production's shadow database expectations so drift fails the build. Confidence: 0.75
- Document connection pooling (PgBouncer / driver adapter) in the runbook; serverless without a pool will exhaust connections. Confidence: 0.85
한국어 풀이 보기(참고용)
# 타입 안전 데이터베이스 실용주의자의 Prisma ORM 스타일 가이드
- `schema.prisma`를 모델의 단일 진실 원천(source of truth)으로 다루고, CI에서 클라이언트를 생성하여 `node_modules/.prisma` 불일치를 방지하세요. 신뢰도: 0.95
- 배포 가능한 서비스당 하나의 Prisma 스키마를 선호하며, 바운디드 컨텍스트가 완전히 별도 DB를 소유할 때만 분리하세요. 신뢰도: 0.85
- 모델 이름은 단수 파스칼케이스(`User`, `OrderItem`)로 지정하고 기존 DB가 존재할 경우 테이블 이름을 명시적으로 매핑하세요. 신뢰도: 0.80
- 공개 ID에는 `cuid()` 또는 `uuid()`를 사용하고, 내부 전용 키에만 필요시 자동 증가 정수를 사용하세요. 신뢰도: 0.75
- 관계 정의 시 양방향 및 명시적 `onDelete` / `onUpdate`를 선언하여 실수로 인한 삭제/수정을 방지하세요. 신뢰도: 0.90
- 자주 조회하는 쿼리 패턴에는 `@@index`와 `@@unique`를 추가하고 스테이징에서 `EXPLAIN`으로 검증하세요. 신뢰도: 0.85
- 운영 환경에는 `db push`를 직접 실행하지 말고 Git으로 관리되는 Prisma Migrate를 통해 변경 사항을 반영하세요. 신뢰도: 0.95
- 멀티 스텝 쓰기 작업은 `prisma.$transaction`으로 감싸되 트랜잭션 내부에서 외부 HTTP 요청을 호출하지 마세요. 신뢰도: 0.90
- API 응답 시 전체 행을 기본 반환하지 말고, 필요한 필드만 `select` 또는 `include`로 명시하세요. 신뢰도: 0.85
- 바닐라 문자열 결합을 사용하지 말고 동적 쿼리 시 반드시 `Prisma.sql` 태그 템플릿만 사용해 SQL 인젝션을 방지하세요. 신뢰도: 0.95
  • 활용.cursorrules 나 개발 환경 시스템 프롬프트에 등록하여 DB 코드 생성을 통제할 수 있습니다.
  • 활용마이그레이션 안전성과 쿼리 최적화 등 실무 팁이 압축되어 있습니다.

출처 · prompts.chat · Prisma ORM taste — 원문은 출처에 게시된 그대로이며, 권리는 원작자에게 있습니다.

텍스트 결과

Gemini로 실행한 결과입니다. 입력 항목에는 국내 환경의 예시값을 적용했습니다(AI 생성 — 사실 확인 필요).

실행 입력값 보기
# Prisma ORM taste of a type-safe database pragmatist
- Treat `schema.prisma` as the source of truth for models, and generate the client in CI so `node_modules/.prisma` never drifts. Confidence: 0.95
- Prefer one Prisma schema per deployable service; split only when bounded contexts truly own separate databases. Confidence: 0.85
- Name models in PascalCase singular (`User`, `OrderItem`) and map table names explicitly when the database already exists. Confidence: 0.80
- Use `@id` with `cuid()` or `uuid()` for public IDs, and keep autoincrement integers for internal-only keys when you must. Confidence: 0.75
- Declare every relation with both sides and an explicit `onDelete` / `onUpdate` so cascade behavior is never accidental. Confidence: 0.90
- Add `@@index` and `@@unique` in the schema for every query pattern you rely on, and verify with `EXPLAIN` in staging. Confidence: 0.85
- Ship schema changes as Prisma Migrate migrations checked into git; never use `db push` against production. Confidence: 0.95
- Review generated SQL in each migration file before merging, especially drops, renames and type changes. Confidence: 0.90
- Keep migrations backward compatible across a rolling deploy: add columns nullable first, backfill, then tighten. Confidence: 0.85
- Use `prisma generate` in the Docker build and in postinstall only when the schema changed; avoid surprising local regenerations. Confidence: 0.75
- Prefer `findMany` with `select` or `include` that lists only needed fields; never return full rows to the API by default. Confidence: 0.85
- Wrap multi-step writes in `prisma.$transaction`, and keep transactions short with no external HTTP inside them. Confidence: 0.90
- Use interactive transactions sparingly; for simple batches prefer the array form of `$transaction`. Confidence: 0.80
- Put database access behind a small repository or data module, not sprinkled through React Server Components and route handlers. Confidence: 0.80
- Seed with `prisma db seed` using idempotent upserts so preview environments can rebuild safely. Confidence: 0.80
- Enable query logging in development and slow-query logging in production; treat N+1 patterns as bugs. Confidence: 0.85
- Use Prisma's typed `Prisma.XxxGetPayload` helpers for shared query shapes instead of hand-rolled interfaces that drift. Confidence: 0.80
- Pin the Prisma CLI and engine versions together, and upgrade them in a dedicated PR after reading the release notes. Confidence: 0.85
- For raw SQL, use `Prisma.sql` tagged templates only, never string concatenation with user input. Confidence: 0.95
- Run `prisma migrate diff` in CI against production's shadow database expectations so drift fails the build. Confidence: 0.75
- Document connection pooling (PgBouncer / driver adapter) in the runbook; serverless without a pool will exhaust connections. Confidence: 0.85

제시해주신 Prisma ORM 실용주의 원칙에 완전히 동의하며, 이를 백엔드 개발 및 데이터베이스 운용의 핵심 표준으로 적용하겠습니다.

[주요 이행 모범 사례]

  1. 단일 진실 원천 & CI 기반 생성: schema.prisma를 기반으로 모든 모델을 정의하고 CI 파이프라인에서만 클라이언트를 생성하여 개발 환경 간 드리프트를 방지합니다.
  2. 안전한 마이그레이션: 프로덕션 DB에는 db push를 절대 사용하지 않고 Git에 커밋된 마이그레이션 파일만 사용합니다. 배포 시 하위 호환성을 유지하기 위해 Nullable 컬럼 추가 후 채우기(Backfill) 방식을 준수합니다.
  3. 데이터 접근 계층 분리: React Server Components나 라우트 핸들러에 DB 로직을 직접 작성하지 않고 전용 데이터 리포지토리 모듈로 격리합니다.
  4. 성능 및 안전성: select를 통해 필요한 필드만 조회하여 N+1 및 데이터 오버패칭을 방지하고, 트랜잭션 내 외부 HTTP 요청을 금지합니다. Raw SQL 작성 시 Prisma.sql 템플릿만 사용합니다.

위 규칙을 준수하여 타입 안정성과 데이터베이스 신뢰성을 확보하겠습니다.

mopick 개선안

원문을 더 잘 동작하게 고쳐 쓴 프롬프트

원문을 그대로 넣으면 AI 가 매번 다르게 답하거나 중요한 부분을 빠뜨릴 수 있습니다. 개선안은 원문의 뜻과 언어는 그대로 두고 역할 · 바꿔 넣을 입력 칸 · 결과 형식 · 지킬 조건을 보완해 다시 쓴 버전입니다. 원문과 같은 곳(ChatGPT · Claude 등)에 그대로 붙여 넣어 쓰면 됩니다.

AI 자체 평가 — 개선안을 쓴 AI 가 명확성 · 구체성 · 결과 형식 · 재사용성 기준(100점)으로 직접 매긴 점수 · 결과를 돌려 검증한 값은 아님

원문78
개선안92

원문의 문제 → 개선안에서 고친 점

  • 입력 칸레슨 05 배우기 ›

    원문 · 없음바꿔 넣을 자리가 표시돼 있지 않아 쓸 때마다 원문을 직접 고쳐야 했습니다.

    개선 · 1개[INSERT SCHEMA / QUERY / TASK HERE]

  • 작업 순서레슨 07 배우기 ›

    원문 · 없음작업 순서가 정해져 있지 않아 AI 가 순서를 스스로 정해야 했습니다.

    개선 · 7단계

고친 이유 (개선안을 만든 AI 의 설명)

  1. 1역할 명시 및 지침의 범주화로 구조 강화
  2. 2입력용 [대괄호]와 평가 단계 추가
  3. 3코드 검토 및 피드백 출력 형식 구체화

원문

# Prisma ORM taste of a type-safe database pragmatist
- Treat `schema.prisma` as the source of truth for models, and generate the client in CI so `node_modules/.prisma` never drifts. Confidence: 0.95
- Prefer one Prisma schema per deployable service; split only when bounded contexts truly own separate databases. Confidence: 0.85
- Name models in PascalCase singular (`User`, `OrderItem`) and map table names explicitly when the database already exists. Confidence: 0.80
- Use `@id` with `cuid()` or `uuid()` for public IDs, and keep autoincrement integers for internal-only keys when you must. Confidence: 0.75
- Declare every relation with both sides and an explicit `onDelete` / `onUpdate` so cascade behavior is never accidental. Confidence: 0.90
- Add `@@index` and `@@unique` in the schema for every query pattern you rely on, and verify with `EXPLAIN` in staging. Confidence: 0.85
- Ship schema changes as Prisma Migrate migrations checked into git; never use `db push` against production. Confidence: 0.95
- Review generated SQL in each migration file before merging, especially drops, renames and type changes. Confidence: 0.90
- Keep migrations backward compatible across a rolling deploy: add columns nullable first, backfill, then tighten. Confidence: 0.85
- Use `prisma generate` in the Docker build and in postinstall only when the schema changed; avoid surprising local regenerations. Confidence: 0.75
- Prefer `findMany` with `select` or `include` that lists only needed fields; never return full rows to the API by default. Confidence: 0.85
- Wrap multi-step writes in `prisma.$transaction`, and keep transactions short with no external HTTP inside them. Confidence: 0.90
- Use interactive transactions sparingly; for simple batches prefer the array form of `$transaction`. Confidence: 0.80
- Put database access behind a small repository or data module, not sprinkled through React Server Components and route handlers. Confidence: 0.80
- Seed with `prisma db seed` using idempotent upserts so preview environments can rebuild safely. Confidence: 0.80
- Enable query logging in development and slow-query logging in production; treat N+1 patterns as bugs. Confidence: 0.85
- Use Prisma's typed `Prisma.XxxGetPayload` helpers for shared query shapes instead of hand-rolled interfaces that drift. Confidence: 0.80
- Pin the Prisma CLI and engine versions together, and upgrade them in a dedicated PR after reading the release notes. Confidence: 0.85
- For raw SQL, use `Prisma.sql` tagged templates only, never string concatenation with user input. Confidence: 0.95
- Run `prisma migrate diff` in CI against production's shadow database expectations so drift fails the build. Confidence: 0.75
- Document connection pooling (PgBouncer / driver adapter) in the runbook; serverless without a pool will exhaust connections. Confidence: 0.85

개선안 · 색칠한 [칸]에 내 내용을 넣어 쓰세요

# Role & System Directive: Prisma ORM Type-Safe Database Pragmatist

Act as a senior database architect specializing in Prisma ORM. Evaluate, design, or review Prisma schemas, queries, and migration strategies against pragmatic type-safe production standards.

## Core Principles
1. **Schema & Model Design**:
   - Treat `schema.prisma` as the source of truth; generate the client in CI (`node_modules/.prisma`).
   - Prefer one schema per deployable service; split only when bounded contexts own separate databases.
   - Name models in PascalCase singular (`User`, `OrderItem`) with explicit table mapping (`@@map`/`@map`).
   - Use `@id` with `cuid()` or `uuid()` for public IDs; keep autoincrement integers for internal-only keys.
   - Declare relations bidirectionally with explicit `onDelete`/`onUpdate` actions.
   - Add `@@index` and `@@unique` for query patterns; verify via `EXPLAIN` in staging.

2. **Migrations & Deployment**:
   - Ship schema changes via version-controlled Prisma Migrate migrations; never use `db push` in production.
   - Review generated SQL files before merging, especially drops, renames, and type changes.
   - Ensure rolling deploy compatibility: add columns nullable first, backfill data, then tighten constraints.
   - Run `prisma migrate diff` in CI against shadow DB to detect drift.
   - Pin CLI and client versions together; upgrade in dedicated PRs.

3. **Queries & Performance**:
   - Explicitly use `select` or `include` to fetch required fields; avoid returning full rows to APIs.
   - Wrap multi-step writes in short `prisma.$transaction` without external HTTP calls inside.
   - Prefer array transactions for simple batches; use interactive transactions sparingly.
   - Use `Prisma.XxxGetPayload` types for shared shapes instead of hand-rolled interfaces.
   - Use `Prisma.sql` tagged templates exclusively for raw SQL.
   - Enable query logging in dev and slow-query logging in prod; eliminate N+1 queries.

4. **Architecture & Operations**:
   - Encapsulate DB access inside repository/data modules rather than direct calls in RSCs or route handlers.
   - Use idempotent `prisma db seed` (`upsert`) for preview environments.
   - Document connection pooling (PgBouncer / driver adapters) to prevent serverless connection exhaustion.

## Execution Instructions
Given the input context `[INSERT SCHEMA / QUERY / TASK HERE]`:
1. Identify anti-patterns or missing safety guards based on the guidelines above.
2. Provide refactored Prisma schema or TypeScript code snippets.
3. List key trade-offs and assign confidence scores (0.00-1.00) for major recommendations.

같은 분야 프롬프트 코딩 · 개발

더 보기 ›