What is Prisma?
Prisma is a modern, type-safe ORM (Object-Relational Mapper) for TypeScript. It provides type-safe queries, automatic migrations, and an intuitive API.
Installation
npm install prisma @prisma/client
npx prisma init --datasource-provider postgresql
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())
email String @unique
name String
role Role @default(USER)
posts Post[]
createdAt DateTime @default(now())
@@map("users")
}
model Post {
id Int @id @default(autoincrement())
title String
content String
published Boolean @default(false)
author User @relation(fields: [authorId], references: [id])
authorId Int
tags Tag[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@map("posts")
}
model Tag {
id Int @id @default(autoincrement())
name String @unique
posts Post[]
@@map("tags")
}
enum Role {
ADMIN
USER
}
Running Migrations
npx prisma migrate dev --name init
npx prisma studio # Visual database editor
Prisma Client Singleton
// lib/prisma.ts
import { PrismaClient } from "@prisma/client";
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined;
};
export const prisma =
globalForPrisma.prisma ??
new PrismaClient({ log: ["query", "error", "warn"] });
if (process.env.NODE_ENV !== "production") {
globalForPrisma.prisma = prisma;
}
CRUD Operations
import { prisma } from "@/lib/prisma";
// CREATE
const newUser = await prisma.user.create({
data: { email: "[email protected]", name: "John Doe" },
});
// READ (single)
const user = await prisma.user.findUnique({
where: { id: 1 },
include: { posts: true },
});
// READ (list with pagination)
const posts = await prisma.post.findMany({
where: { published: true },
orderBy: { createdAt: "desc" },
take: 10,
skip: (page - 1) * 10,
include: { author: { select: { name: true } } },
});
// UPDATE
const updated = await prisma.user.update({
where: { id: 1 },
data: { name: "Updated Name" },
});
// DELETE
await prisma.user.delete({ where: { id: 1 } });
// COUNT
const total = await prisma.post.count({ where: { published: true } });
Önemli Noktalar
- Prisma is a type-safe modern ORM for TypeScript
- Data models are defined in prisma/schema.prisma
- npx prisma migrate dev updates the database schema
- The Singleton pattern prevents PrismaClient issues during hot reload