$devvkit learn --librarie prisma-guide
Prisma Guide
[orm][database][typescript]
JavaScript / TypeScript
Install
npm install prisma @prisma/client npx prisma init
Prisma replaces traditional ORMs with a type-safe query API. Define schema in Prisma Schema Language.
Run prisma generate to get a fully typed client. Queries are validated at compile time.
Supports PostgreSQL, MySQL, SQLite, SQL Server, MongoDB, and CockroachDB.
Setup
Init— Create prisma directory.
npx prisma init
Studio— Visual database browser.
npx prisma studio
Schema Design
Schema— Define a User model.
model User {
id String @id @default(cuid())
email String @unique
name String?
posts Post[]
createdAt DateTime @default(now())
}Related model— Define Post with relation.
model Post {
id String @id @default(cuid())
title String
author User @relation(fields: [authorId], references: [id])
authorId String
}CRUD
Create record— Insert data.
const user = await prisma.user.create({
data: { email: 'alice@example.com', name: 'Alice' },
});Find unique— Get by unique column.
const user = await prisma.user.findUnique({
where: { email: 'alice@example.com' },
});Find with filters— Query with conditions.
const users = await prisma.user.findMany({
where: { name: { contains: 'Ali' } },
orderBy: { createdAt: 'desc' },
take: 10,
});Update— Modify existing data.
await prisma.user.update({
where: { id: 'abc123' },
data: { name: 'Alice Updated' },
});Delete— Remove a record.
await prisma.user.delete({ where: { id: 'abc123' } });Relations
Include relations— Eager load related.
const user = await prisma.user.findUnique({
where: { id: 'abc123' },
include: { posts: true },
});Transaction— Atomic operations.
const [user, post] = await prisma.([
prisma.user.create({ data: { email: 'x@x.com' } }),
prisma.post.create({ data: { title: 'X', authorId: '...' } }),
]);Migrations
Migrate— Create and apply migration.
npx prisma migrate dev --name add_users