Loading Blog Article...
Loading Blog Article...
Loading Blog Article...
Managing database migrations effectively is crucial for maintaining data integrity and smooth application deployment. This guide covers best practices for using Prisma Migrate to handle database schema changes professionally.
Prisma Migrate is a powerful database migration tool that helps developers maintain and version their database schema. It automatically generates SQL migration files based on changes to your Prisma schema.
Let's examine a basic Prisma schema that defines three interconnected models:
// schema.prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
posts Post[]
profile Profile?
}
model Profile {
id Int @id @default(autoincrement())
bio String?
user User @relation(fields: [userId], references: [id])
userId Int @unique
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
}Let's explore the key Prisma features demonstrated in this schema in detail:
Let's break down this migration workflow step by step:
The workflow is iterative - if issues are found during testing, developers can make additional schema changes and generate new migrations until the desired result is achieved.
The following diagram shows the complete migration workflow:
This example demonstrates adding a timestamp field to track user creation dates:
// Original model
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
// Adding a new field
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
created DateTime @default(now())
}Key points about this schema change:
Here's a detailed migration script that handles both the schema change and data transformation:
// migration.ts
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
// Update existing records with current timestamp
await prisma.user.updateMany({
data: {
created: new Date(),
},
})
// Complex data transformation for specific users
const users = await prisma.user.findMany({
where: {
email: {
contains: '@example.com'
}
}
})
for (const user of users) {
await prisma.profile.create({
data: {
userId: user.id,
bio: `Default bio for ${user.name}`
}
})
}
}
main()
.catch((e) => {
console.error(e)
process.exit(1)
})
.finally(async () => {
await prisma.$disconnect()
})This migration script demonstrates several important patterns:
Here's an example of managing enum types in your schema:
enum Role {
USER
ADMIN
}
model User {
id Int @id @default(autoincrement())
email String @unique
role Role @default(USER)
}
// Migration to add new role
enum Role {
USER
ADMIN
MODERATOR
}Important considerations for enum changes:
This example shows how to create related records efficiently:
// Creating related records
async function createUserWithPosts() {
const user = await prisma.user.create({
data: {
email: 'user@example.com',
name: 'John Doe',
posts: {
create: [
{
title: 'First Post',
content: 'Hello World!',
published: true
},
{
title: 'Draft Post',
content: 'Work in progress...',
published: false
}
]
}
},
include: {
posts: true
}
})
console.log(user)
}This code demonstrates several advanced Prisma features:
Here's a comprehensive database seeding script:
// seed.ts
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function seed() {
// Clean existing data
await prisma.post.deleteMany()
await prisma.profile.deleteMany()
await prisma.user.deleteMany()
// Create new data
const alice = await prisma.user.create({
data: {
email: 'alice@prisma.io',
name: 'Alice',
profile: {
create: {
bio: 'I love databases!'
}
},
posts: {
create: [
{
title: 'Prisma Makes Database Easy',
published: true
}
]
}
}
})
console.log({ alice })
}
seed()
.catch((e) => {
console.error(e)
process.exit(1)
})
.finally(async () => {
await prisma.$disconnect()
})This seeding script showcases several best practices:
Finally, here's a production-ready deployment script:
# Production deployment script
#!/bin/bash
# Backup database
pg_dump $DATABASE_URL > backup.sql
# Run migrations
npx prisma migrate deploy
# If migration fails, restore from backup
if [ $? -ne 0 ]; then
echo "Migration failed, restoring from backup..."
psql $DATABASE_URL < backup.sql
exit 1
fi
# Run seed if needed
npx prisma db seedThis deployment script implements several crucial safety measures:
Implement these monitoring practices:
Following these best practices ensures smooth database migrations and maintains data integrity across your application's lifecycle. Remember to always test thoroughly in development and staging environments before applying changes to production.
For more information, consult the official Prisma documentation.