Seeding and Managing Migrations
Database seeding populates your development environment with realistic data. Migrations track schema changes over time like version control for your database.
Prisma Seed Script
// prisma/seed.ts
import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';
const db = new PrismaClient();
async function main() {
// Create admin user
const admin = await db.user.upsert({
where: { email: 'admin@example.com' },
update: {},
create: {
name: 'Admin User',
email: 'admin@example.com',
password: await bcrypt.hash('password', 10),
role: 'ADMIN',
},
});
// Create categories
const categories = await Promise.all([
db.category.upsert({
where: { slug: 'tutorials' },
update: {},
create: { name: 'Tutorials', slug: 'tutorials' },
}),
db.category.upsert({
where: { slug: 'news' },
update: {},
create: { name: 'News', slug: 'news' },
}),
]);
// Create sample posts
for (let i = 1; i <= 10; i++) {
await db.post.upsert({
where: { slug: `sample-post-${i}` },
update: {},
create: {
title: `Sample Post ${i}`,
slug: `sample-post-${i}`,
content: `This is the content for sample post ${i}. `.repeat(20),
excerpt: `Excerpt for sample post ${i}`,
published: true,
publishedAt: new Date(Date.now() - i * 86400000),
authorId: admin.id,
categoryId: categories[i % 2].id,
},
});
}
console.log('Database seeded successfully');
}
main()
.catch(console.error)
.finally(() => db.$disconnect());
// package.json
{
"prisma": {
"seed": "ts-node --compiler-options '{\"module\":\"CommonJS\"}' prisma/seed.ts"
}
}
npx prisma db seed
Migration Workflow
# 1. Modify schema.prisma
# 2. Create migration
npx prisma migrate dev --name add_view_count_to_posts
# 3. Prisma generates the SQL migration file
# prisma/migrations/20241015_add_view_count_to_posts/migration.sql
# 4. Apply in production (CI/CD)
npx prisma migrate deploy
Deploying Migrations Safely
In your deployment script:
#!/bin/bash
# Run migrations before starting the server
npx prisma migrate deploy
# Then start the application
npm run start
Never run prisma migrate dev in production — it prompts interactively and may reset data. Always use migrate deploy in CI/CD pipelines.