0Pricing
Next.js 15 Fullstack Web Apps · 강의

Prisma 스키마 설계와 마이그레이션

Prisma 스키마 언어로 데이터베이스 스키마를 설계하고 데이터베이스 마이그레이션을 관리합니다.

Prisma 스키마 설계와 마이그레이션은(는) CoddyKit의 무료 Next.js 15 Fullstack Web Apps 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Next.js 15 Fullstack Web Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Next.js 15 Fullstack Web Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Prisma Schema: Your Database Blueprint

Welcome back! In this lesson, we'll dive into designing your database schema using Prisma Schema Language and managing changes with migrations.

The schema.prisma file is the heart of your Prisma setup. It's a single source of truth for your database schema and how your application models interact with it.

The Core Schema Blocks

Every schema.prisma file starts with two main blocks: datasource and generator.

  • datasource: Defines your database connection (e.g., PostgreSQL, MySQL, SQLite).
  • generator: Specifies which Prisma Client to generate, allowing you to interact with your database in a type-safe way.

Here's a basic structure:

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

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

Defining Models: Your Data Structure

After the core blocks, you define your models. A Prisma model maps directly to a table in your database and represents the structure of your data.

The model keyword is used, followed by the model's name (singular, PascalCase, e.g., User or Product).

model User {
  id    String @id @default(uuid())
  email String @unique
  name  String?
}

Fields and Data Types

Inside each model, you define fields, which correspond to columns in your database table. Each field has a name and a data type.

Prisma supports common scalar types like String, Int, Boolean, DateTime, Float, Json, and more. For example, id is often a String or Int.

model Product {
  id          Int      @id @default(autoincrement())
  name        String
  description String?
  price       Float
  published   Boolean  @default(false)
  createdAt   DateTime @default(now())
}

Field Modifiers and Attributes

Fields can have modifiers and attributes to add extra meaning or constraints:

  • ? (Optional): Makes a field nullable.
  • [] (List): Indicates a list of values (e.g., String[]).
  • @id: Marks a field as the primary key.
  • @unique: Ensures all values in this field are unique.
  • @default(): Sets a default value.
  • @updatedAt: Automatically updates a DateTime field on every record update.
model Post {
  id        String    @id @default(uuid())
  title     String
  content   String?
  published Boolean   @default(false)
  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt
}

Connecting Data: Relations

Databases are all about related data! Prisma makes it easy to define relationships between your models, like a user having many posts (one-to-many).

You define a relation by linking fields between models using the @relation attribute. This attribute takes arguments like fields (the foreign key) and references (the primary key it refers to).

model User {
  id        String    @id @default(uuid())
  email     String    @unique
  name      String?
  posts     Post[]    // A user can have many posts
  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt
}

model Post {
  id        String    @id @default(uuid())
  title     String
  content   String?
  published Boolean   @default(false)
  author    User?     @relation(fields: [authorId], references: [id]) // Relation to User
  authorId  String?   // Foreign key for the User
  createdAt DateTime  @default(now())
  updatedAt DateTime  @updatedAt
}

Evolving Your Database: Migrations

As your application grows, your database schema will change. Migrations are how Prisma tracks these changes and applies them to your actual database in a controlled, versioned way.

Prisma Migrate generates SQL files based on the differences between your schema.prisma and your current database state, ensuring your database evolves predictably.

Generating Your First Migration

To create a new migration, you use the Prisma CLI command npx prisma migrate dev. You should give your migration a descriptive name.

This command does three things:

  1. Compares your schema.prisma to the database.
  2. Generates a new migration file (SQL) if there are changes.
  3. Applies the new migration to your development database.

Try it after making a change to your schema:

npx prisma migrate dev --name added_user_profile

Applying Migrations & Schema Sync

Besides prisma migrate dev for development, there are other commands:

  • npx prisma migrate deploy: Applies all pending migrations to the database. This is typically used in production environments.
  • npx prisma db push: Pushes the current schema state to the database without creating a migration file. Useful for rapid prototyping in development when you don't need migration history.

Choose the right command for your workflow!

npx prisma migrate deploy

npx prisma db push

Quick Check: Schema Updates

You've just added a new field role to your User model in schema.prisma and want to apply this change to your development database while also creating a migration file to track this change. Which command should you use?

Schema & Migrations: Key Takeaways

Great job! You've learned how to design your database with Prisma Schema Language and manage its evolution with migrations.

  • The schema.prisma file is your single source of truth for database structure.
  • Models define tables, and fields define columns with various types and attributes.
  • Relations connect your models, reflecting real-world data links.
  • Prisma Migrate helps you track and apply schema changes reliably across environments.

Next, we'll learn how to perform CRUD operations (Create, Read, Update, Delete) using the Prisma Client.

자주 묻는 질문

“Prisma 스키마 설계와 마이그레이션” 강의는 무료인가요?

네 — “Prisma 스키마 설계와 마이그레이션” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Next.js 15 Fullstack Web Apps 강의 전체를 잠금 해제할 수 있습니다. Next.js 15 Fullstack Web Apps 강의에는 총 4개의 강의가 포함되어 있습니다.

“Prisma 스키마 설계와 마이그레이션”에서 뭘 배우나요?

Prisma 스키마 언어로 데이터베이스 스키마를 설계하고 데이터베이스 마이그레이션을 관리합니다. 브라우저에서 직접 실행하는 실습 코드로 Next.js 15 Fullstack Web Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Next.js 15 Fullstack Web Apps을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Next.js 15 Fullstack Web Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“Prisma 스키마 설계와 마이그레이션” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Next.js 15 Fullstack Web Apps 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Next.js 15 Fullstack Web Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Prisma ORM 소개
  2. Prisma 스키마 설계와 마이그레이션
  3. Prisma 클라이언트를 사용한 CRUD 작업
  4. Prisma의 관계와 고급 질의
← Next.js 15 Fullstack Web Apps(으)로 돌아가기