Prisma Migration and Seeding
Prisma is a powerful ORM (Object-Relational Mapping) tool for Node.js that makes working with databases a breeze. Prisma provides an easy way to define your database schema, generate migrations, and seed your database with initial data. In this guide, we'll cover migrations and seeding using Prisma, and explore how they work in a Docker environment.
Migrations and Seeding Overview
- Migrations: Prisma migrations allow you to evolve your database schema over time by applying changes incrementally.
- Seeding: Seeding is the process of populating your database with initial or test data to help with development or testing.
Wonder How Migrations and Seeding Work in Docker?
When we ran npm run docker:compose
, Prisma automatically executed migrations to populate our User
table, and also seeded it with initial data. This was made possible by a script called entrypoint-dev.sh
, which was called from the Dockerfile.dev
.
The entrypoint file is needed because it defines the series of commands that should be executed when the container starts. In this case, it makes sure that our Prisma migrations and seeding are applied as soon as the Docker container spins up.
Practicing Migration and Seeding
Let's practice generating a new migration and seeding data. I won't go too deep into the Prisma syntax, but this should give you a clear idea of the steps involved.
Step 1: Update Your Prisma Schema
Navigate to your Prisma schema file at prisma/schema.prisma
and add an email
column to the User
model.
model User {
id Int @id @default(autoincrement())
username String
email String? @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Step 2: Generate Prisma Client
Exit the terminal running your backend, and run:
npm run prisma:generate
This command generates the Prisma client with the latest schema changes, ensuring that your TypeScript code on the host machine is in sync with the updated schema.
Step 3: Update Your Seeding Script
Now, let's update the seeding script in prisma/seed.ts
to add email values to our users:
Note: If you don't want to seed data every time you run Docker Compose, you can simply comment out the
npx prisma db seed
command in the entrypoint-dev.sh file.
async function createUsers() {
const usernames = ['goat', 'strawberry'];
const emails = ['goat@example.com', 'strawberry@example.com'];
for (let i = 0; i < usernames.length; i++) {
await prisma.user.create({
data: {
username: usernames[i],
email: emails[i],
},
});
}
}
Note: The line
await prisma.user.deleteMany();
deletes all user data every time we rundocker-compose up
. If you don't want to lose existing data, simply comment out this line.
Step 4: Update the Entry Point Script
Go to the entrypoint-dev.sh
file in your root directory, and update the migration command as follows:
npx prisma migrate dev --name added_email
This command creates a new migration with the name added_email
that adds the email
field to the User
model.
Step 5: Run Docker Compose
Finally, run the docker compose command:
npm run docker:compose
It will stop at the point shown in the following warning:
This is because we added a @unique
constraint in the schema, and Prisma is asking for your confirmation to continue. To do this, we need to interact with Docker by entering the Y command. To proceed, follow these steps:
- Open a new terminal and type
docker ps
to list the currently running containers.
- Type
docker attach <CONTAINER ID of express-server>
i.e.docker attach 33e27b4273e7
- Type
y
to confirm. Your migration will be applied, and finally, the seeding process will proceed.
- A new migration file will be generated under
prisma/migrations
in both the host and the Docker container.
- Host:
- Docker container (
Files tab -> usr -> src -> app
):
Step 6: Check your endpoint
Open a browser and go to /v1/users (opens in a new tab); the seeded data will be displayed with updated schema.
💡 How migrations work on both staging and production.
i.e. When a new migration file is generated under
prisma/migrations
and you merge it into the staging branch, it will automatically trigger your CI/CD pipeline. During this process, thenpx prisma migrate deploy
command in yourmain.yml
file will be executed. This command reads the new migration file and applies the schema changes to your staging database.
Wrap-Up
And there you have it! You've updated your schema, applied a new migration, regenerated Prisma client files, and seeded your database. These steps allow you to easily keep your schema, migrations, and data in sync during development.