Working with Enums
1. Defining Schema Enums
enum Role {
USER
EDITOR
ADMIN @map("administrator")
}
| Aspect | Detail |
|---|---|
| Naming | PascalCase enum, UPPER_SNAKE values |
| Mapping | @map per value, @@map for type name |
2. Using Enum Fields
| Pattern | Example |
|---|---|
| Required | role Role |
| Optional | role Role? |
| List | roles Role[] (PG only) |
3. Setting Enum Defaults
role Role @default(USER)
| Note | Detail |
|---|---|
| Migration | Default applied at DB level via DEFAULT clause |
| Change default | Requires migration |
4. Accessing Enum Values
import { Role } from "@prisma/client";
await prisma.user.create({ data: { email: "a@b.io", role: Role.ADMIN } });
| Source | How |
|---|---|
| Type-safe enum | Imported from generated client |
| String literal | Also accepted at runtime |
5. Filtering by Enum Values
| Operator | Example |
|---|---|
| Equality | { role: Role.ADMIN } |
| In | { role: { in: [Role.ADMIN, Role.EDITOR] } } |
| Not in | { role: { notIn: [Role.USER] } } |
| Not | { role: { not: Role.USER } } |
6. Updating Enum Fields
await prisma.user.update({
where: { id: 1 },
data: { role: Role.EDITOR }
});
| Pattern | Notes |
|---|---|
| Bulk update | updateMany({ where:{role:USER}, data:{role:EDITOR} }) |
| Conditional | Use where filters to scope |
7. Migrating Enum Values
| Change | Migration Safety |
|---|---|
| Add value | Safe; appended to enum |
| Rename | Drops + recreates; data migration needed |
| Remove | Fails if rows still reference it |
| PG-specific | Generates ALTER TYPE ... ADD VALUE |
8. Using Native Database Enums
| DB | Behavior |
|---|---|
| PostgreSQL | Generates real CREATE TYPE |
| MySQL | Inline ENUM column |
| SQLite/Mongo | Stored as string |
9. Handling Enum Type Safety
| Tip | Detail |
|---|---|
| Exhaustive switches | TypeScript narrows enum unions |
| Zod / Valibot | Use z.nativeEnum(Role) |
Avoid as Role | Validate untrusted input |
10. Converting Strings to Enums
function toRole(value: string): Role {
if ((Object.values(Role) as string[]).includes(value)) return value as Role;
throw new Error(`Invalid role: ${value}`);
}
| Strategy | Detail |
|---|---|
| Runtime guard | Validate before passing to Prisma |
| Schema parsing | Use Zod nativeEnum for DTOs |