Prisma ORM
Prisma ORM is a next-generation ORM for TypeScript/JavaScript. It features type safety, auto-generated client, and intuitive data modeling language, supporting PostgreSQL, MySQL, SQLite, MongoDB, and SQL Server. It's a modern ORM designed with developer experience as the top priority.
Library
Prisma ORM
Overview
Prisma ORM is a next-generation ORM for TypeScript/JavaScript. It features type safety, auto-generated client, and intuitive data modeling language, supporting PostgreSQL, MySQL, SQLite, MongoDB, and SQL Server. It's a modern ORM designed with developer experience as the top priority.
Details
Prisma adopts a different approach from traditional ORMs. With its schema-first design, you declaratively define database schemas and automatically generate type-safe client code from them. This significantly reduces runtime errors and improves developer productivity.
Key Features
- Type Safety: Complete integration with TypeScript
- Auto Migrations: Safe application of schema changes
- Prisma Studio: Visual database management tool
- Rich Relations: Easy expression of complex data relationships
- Performance Optimization: Efficient query generation
Pros and Cons
Pros
- Overwhelming type safety in TypeScript development
- Intuitive query syntax with low learning curve
- Safe schema management through auto-generated migrations
- Excellent performance in serverless environments
- Active community and comprehensive documentation
Cons
- Schema-first approach requires effort for existing database migration
- Generated client can become large in some cases
- Limitations in expressing complex SQL statements
- Limited enterprise track record as a relatively new tool
Reference Pages
Code Examples
Basic Setup
npm install prisma @prisma/client
npx prisma init
Schema Definition
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
content String
authorId Int
author User @relation(fields: [authorId], references: [id])
}
Client Generation and Queries
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
// Create user
const user = await prisma.user.create({
data: {
name: 'John Doe',
email: '[email protected]',
posts: {
create: {
title: 'First Post',
content: 'My first post using Prisma'
}
}
}
})
// Get user with posts
const userWithPosts = await prisma.user.findUnique({
where: { email: '[email protected]' },
include: { posts: true }
})
Transactions
const result = await prisma.$transaction(async (tx) => {
const user = await tx.user.create({
data: { name: 'Jane Smith', email: '[email protected]' }
})
const post = await tx.post.create({
data: {
title: 'Transaction Test',
content: 'Post created within transaction',
authorId: user.id
}
})
return { user, post }
})
Complex Queries
// Search with pagination
const posts = await prisma.post.findMany({
where: {
title: { contains: 'Prisma' },
author: { email: { endsWith: '@example.com' } }
},
include: { author: true },
orderBy: { createdAt: 'desc' },
skip: 10,
take: 5
})
// Aggregation queries
const postCount = await prisma.post.groupBy({
by: ['authorId'],
_count: { id: true },
having: { id: { _count: { gt: 5 } } }
})
Migrations
# Generate migration
npx prisma migrate dev --name add_user_model
# Apply migration to production
npx prisma migrate deploy
# Reset schema (development only)
npx prisma migrate reset