Skip to main content

Using Prisma Migrate

Creating the database schema

In this guide, you'll use Prisma Migrate to create the tables in your database.

To do so, first add the following Prisma data model to your Prisma schema in prisma/schema.prisma:

prisma/schema.prisma
model Post {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
}

model Profile {
id Int @id @default(autoincrement())
bio String?
user User @relation(fields: [userId], references: [id])
userId Int @unique
}

model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
profile Profile?
}

This data model defines three models (which will be mapped to tables in the underlying database):

  • Post
  • Profile
  • User

It also defines two relations:

  • A one-to-many relation between User and Post (i.e. "one user can have many posts")
  • A one-to-one relation between User and Profile (i.e. "one user can have one profile")

To map your data model to the database schema, you need to use the prisma migrate CLI commands:

npx prisma migrate dev --name init

This command did two things:

  1. It generated a new SQL migration file for this migration
  2. It ran the SQL migration file against the database

You can inspect the generated SQL migration file in the newly created prisma/migrations directory.

Explore your database in Prisma Studio

Prisma Studio is a visual editor for your database. You can open it with the following command in your terminal:

npx prisma studio

Since you just created the database, you won't see any records but you can take a look at the empty User, Post and Profile tables.

Great, you now created three tables in your database with Prisma Migrate. In the next section, you'll learn how to install Prisma Client which lets you send queries to your database from your TypeScript app.