🗄️ Databases

Prisma

Next-generation Node.js and TypeScript ORM

A next-generation ORM for Node.js and TypeScript. Provides type-safe queries, automatic migrations, and intuitive data modeling to maximize developer experience (DX).

📖 Detailed Explanation

Prisma is a next-generation database toolkit designed to resolve the complexity of existing ORMs (such as Sequelize and TypeORM). It simplifies database work through declarative schema definition, automatic type generation, and an intuitive API.

Prisma Schema is the core file that defines the data model. When you declare models, relations, and database connections here, Prisma automatically generates TypeScript types and a query client. This allows query errors to be caught at compile time.

Prisma Client is an automatically generated, type-safe query builder. With intuitive methods such as findMany, create, and update, along with autocompletion, you can build complex queries without writing SQL directly.

Prisma Migrate is a migration system that tracks schema changes and applies them to the database. In development, you iterate quickly with prisma migrate dev, and in production, you deploy safely with prisma migrate deploy.

Prisma Studio is a browser-based database GUI that lets you view and edit data visually. It supports a variety of databases, including PostgreSQL, MySQL, SQLite, MongoDB, and SQL Server.

💻 Code Example

// prisma/schema.prisma - Prisma 스키마 파일

// 데이터베이스 연결 설정
datasource db {
  provider = "postgresql"  // postgresql, mysql, sqlite, mongodb
  url      = env("DATABASE_URL")
}

// Prisma Client 생성 설정
generator client {
  provider = "prisma-client-js"
}

// 사용자 모델
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

  // 관계: 1:N (User -> Post)
  posts     Post[]
  profile   Profile?  // 1:1 관계

  @@index([email])
  @@map("users")  // 테이블명 매핑
}

// 게시글 모델
model Post {
  id          Int       @id @default(autoincrement())
  title       String
  content     String?
  published   Boolean   @default(false)
  authorId    Int
  createdAt   DateTime  @default(now())

  // 관계: N:1 (Post -> User)
  author      User      @relation(fields: [authorId], references: [id], onDelete: Cascade)

  // N:M 관계 (Post <-> Category)
  categories  Category[]

  @@index([authorId])
  @@map("posts")
}

// 카테고리 모델 (N:M 관계)
model Category {
  id    Int     @id @default(autoincrement())
  name  String  @unique
  posts Post[]

  @@map("categories")
}

// 프로필 모델 (1:1 관계)
model Profile {
  id     Int     @id @default(autoincrement())
  bio    String?
  userId Int     @unique
  user   User    @relation(fields: [userId], references: [id])

  @@map("profiles")
}

// Enum 정의
enum Role {
  USER
  ADMIN
  MODERATOR
}
// Prisma Client 사용 예제 - TypeScript
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

// ============================================
// CRUD 기본 작업
// ============================================

// 사용자 생성 (Create)
async function createUser() {
  const user = await prisma.user.create({
    data: {
      email: 'alice@example.com',
      name: 'Alice',
      password: 'hashedPassword123',
      // 관계 데이터도 함께 생성
      posts: {
        create: [
          { title: '첫 번째 글', content: '안녕하세요!' },
          { title: '두 번째 글', published: true }
        ]
      },
      profile: {
        create: { bio: '개발자입니다.' }
      }
    },
    // 관계 데이터 포함하여 반환
    include: {
      posts: true,
      profile: true
    }
  })
  return user
}

// 조회 (Read) - 다양한 필터링
async function getUsers() {
  // 조건부 조회
  const users = await prisma.user.findMany({
    where: {
      OR: [
        { email: { contains: '@gmail.com' } },
        { role: 'ADMIN' }
      ],
      posts: {
        some: { published: true }  // 게시된 글이 있는 사용자
      }
    },
    select: {
      id: true,
      name: true,
      email: true,
      _count: {
        select: { posts: true }  // 게시글 수
      }
    },
    orderBy: { createdAt: 'desc' },
    take: 10,  // LIMIT
    skip: 0    // OFFSET
  })
  return users
}

// 단일 조회 (없으면 에러)
async function getUserOrThrow(id: number) {
  const user = await prisma.user.findUniqueOrThrow({
    where: { id },
    include: { posts: { where: { published: true } } }
  })
  return user
}

// 업데이트 (Update)
async function updateUser(id: number) {
  const user = await prisma.user.update({
    where: { id },
    data: {
      name: 'Alice Kim',
      // 관계 데이터 수정
      posts: {
        updateMany: {
          where: { published: false },
          data: { published: true }
        }
      }
    }
  })
  return user
}

// 삭제 (Delete)
async function deleteUser(id: number) {
  // Cascade 설정으로 관련 posts도 삭제됨
  await prisma.user.delete({
    where: { id }
  })
}

// ============================================
// 트랜잭션
// ============================================

async function transferPoints(fromId: number, toId: number, amount: number) {
  // Interactive Transaction
  const result = await prisma.$transaction(async (tx) => {
    // 1. 포인트 차감
    const sender = await tx.user.update({
      where: { id: fromId },
      data: { points: { decrement: amount } }
    })

    if (sender.points < 0) {
      throw new Error('포인트가 부족합니다')
    }

    // 2. 포인트 증가
    const receiver = await tx.user.update({
      where: { id: toId },
      data: { points: { increment: amount } }
    })

    return { sender, receiver }
  })

  return result
}

// ============================================
// Raw SQL (필요시)
// ============================================

async function rawQuery() {
  // 타입 안전 Raw 쿼리
  const users = await prisma.$queryRaw`
    SELECT * FROM users
    WHERE email LIKE ${'%@gmail.com'}
    LIMIT 10
  `
  return users
}

// 연결 종료 (앱 종료 시)
process.on('beforeExit', async () => {
  await prisma.$disconnect()
})
# Prisma CLI 명령어 모음

# ============================================
# 설치 및 초기화
# ============================================

# Prisma 설치
npm install prisma --save-dev
npm install @prisma/client

# 프로젝트 초기화 (schema.prisma 생성)
npx prisma init

# 특정 DB로 초기화
npx prisma init --datasource-provider postgresql


# ============================================
# 마이그레이션 (개발 환경)
# ============================================

# 스키마 변경 후 마이그레이션 생성 및 적용
npx prisma migrate dev --name init
npx prisma migrate dev --name add_user_role

# 마이그레이션만 생성 (적용 안함)
npx prisma migrate dev --create-only

# 마이그레이션 상태 확인
npx prisma migrate status


# ============================================
# 마이그레이션 (프로덕션)
# ============================================

# 프로덕션 배포 (CI/CD에서 실행)
npx prisma migrate deploy

# 마이그레이션 리셋 (주의: 데이터 삭제!)
npx prisma migrate reset


# ============================================
# Prisma Client 생성
# ============================================

# 스키마 기반 Client 재생성
npx prisma generate

# 스키마 변경 시 자동 재생성 (개발용)
npx prisma generate --watch


# ============================================
# 데이터베이스 작업
# ============================================

# DB 스키마를 Prisma 스키마로 가져오기 (기존 DB)
npx prisma db pull

# Prisma 스키마를 DB에 직접 적용 (마이그레이션 없이)
npx prisma db push

# 시드 데이터 실행
npx prisma db seed


# ============================================
# Prisma Studio (GUI)
# ============================================

# 브라우저에서 데이터 관리
npx prisma studio

# 특정 포트로 실행
npx prisma studio --port 5555


# ============================================
# 기타 유용한 명령어
# ============================================

# 스키마 포맷팅
npx prisma format

# 스키마 유효성 검사
npx prisma validate

# Prisma 버전 확인
npx prisma version

🗣️ Say It Like This in Practice

💬 In a Tech Stack Selection Meeting
"Let's go with Prisma for the ORM. TypeScript types are generated automatically, so runtime errors drop sharply. A single schema file manages the models, types, and migrations. And unlike Sequelize, you don't need to create multiple model files, so maintenance is easier too."
💬 In a code review
"This query looks like it will cause an N+1 Query Problem. When you call findMany, fetch the related data all at once with include. Prisma automatically optimizes it into a JOIN query. Or use select to fetch only the fields you need, which also prevents over-fetching."
💬 In a Deployment Pipeline Discussion
"I added a prisma migrate deploy step to CI/CD. The deployment is set to stop if a migration fails. In development, you can change things freely with migrate dev, but in production you must apply changes only with migrate deploy to be safe."

⚠️ Cautions & Best Practices

❌
N+1 Query Problem

Do not run individual queries inside a loop. Preload the related data with include or select, or fetch it all at once with findMany.

❌
Managing the PrismaClient Instance

Do not use new PrismaClient() on every request. Manage it as a singleton, or in Next.js, cache it on the global object. Otherwise the connection pool will be exhausted.

❌
Do Not Change the Migration Order

You must not manually change the order or contents of generated migration files. If there is a problem, resolve it with a new migration.

✅
Prisma Best Practices

Run generate when the schema changes, use $transaction for transactions, manage sensitive information with env(), and check data with Prisma Studio.

🔗 Related Terms

📚 Learn More