Prisma Migrations & Queries
Schema conventions
Models use PascalCase. Fields use camelCase. Always include createdAt and updatedAt:
prisma
model User {
id String @id @default(cuid())
email String @unique
name String?
posts Post[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
Relations use explicit naming:
prisma
model Post {
id String @id @default(cuid())
title String
author User @relation(fields: [authorId], references: [id], onDelete: Cascade)
authorId String
}
Migration workflow
- •Edit
prisma/schema.prisma - •Generate migration:
npx prisma migrate dev --name descriptive-name - •If migration fails, check the error and adjust schema. Do not use
--force. - •After migration succeeds:
npx prisma generate
Migration names use kebab-case describing the change: add-user-email-index, create-post-table.
Query patterns
Use Prisma Client with explicit select or include — never fetch all fields by default:
typescript
// Good: explicit select
const user = await prisma.user.findUnique({
where: { id },
select: { id: true, email: true, name: true }
});
// Good: explicit include for relations
const userWithPosts = await prisma.user.findUnique({
where: { id },
include: { posts: { orderBy: { createdAt: "desc" }, take: 10 } }
});
Seed data
Seed file at prisma/seed.ts. Use upsert for idempotent seeding:
typescript
await prisma.user.upsert({
where: { email: "admin@example.com" },
update: {},
create: { email: "admin@example.com", name: "Admin" }
});
Run: npx prisma db seed