Deprecated in Prisma ORM v7. Configure the connection URL in Prisma Config instead: see datasource.url. Existing schemas continue to work, but you should migrate to Prisma Config.
shadowDatabaseUrl
No
String (URL)
Deprecated in Prisma ORM v7. Configure the shadow database URL in Prisma Config instead: see datasource.shadowDatabaseUrl.
directUrl
No
String (URL)
Deprecated in Prisma ORM v7. Configure the direct connection URL in Prisma Config instead: see datasource.directUrl.
relationMode
No
String (foreignKeys, prisma)
Sets whether referential integrity is enforced by foreign keys in the database or emulated in the Prisma Client.
In preview in versions 3.1.1 and later. The field is named relationMode in versions 4.5.0 and later, and was previously named referentialIntegrity.
As of Prisma ORM v7, the url, directUrl, and shadowDatabaseUrl fields in the Prisma schema datasource block are deprecated. Configure these fields in Prisma Config instead.
In this example, the target database is available with the following credentials:
User: johndoe
Password: mypassword
Host: localhost
Port: 5432
Database name: mydb
Schema name: public
datasource db { provider = "postgresql"}
When running a Prisma CLI command that needs the database connection URL (e.g. prisma generate), you need to make sure that the DATABASE_URL environment variable is set.
One way to do so is by creating a .env file with the following contents. Note that the file must be in the same directory as your schema.prisma file to automatically picked up the Prisma CLI.
This is the default generator for Prisma ORM 6.x and earlier versions. Learn more about generators.
A generator block accepts the following fields:
Name
Required
Type
Description
provider
Yes
prisma-client-js
Describes which generator to use. This can point to a file that implements a generator or specify a built-in generator directly.
output
No
String (file path)
Determines the location for the generated client, learn more. Default: node_modules/.prisma/client
previewFeatures
No
List of Enums
Use intellisense to see list of currently available Preview features (Ctrl+Space in Visual Studio Code) Default: none
engineType
No
Enum (library or binary)
Defines the query engine type to download and use. Default: library
binaryTargets
No
List of Enums (see below)
Specify the OS on which the Prisma Client will run to ensure compatibility of the query engine. Default: native
moduleFormat
No
Enum (cjs or esm)
Defines the module format of the generated Prisma Client. This field is available only with prisma-client generator.
important
We recommend defining a custom output path, adding the path to .gitignore, and then making sure to run prisma generate via a custom build script or postinstall hook.
The ESM-first client generator that offers greater control and flexibility across different JavaScript environments. It generates plain TypeScript code into a custom directory, providing full visibility over the generated code. Learn more about the new prisma-client generator.
The prisma-client generator will be the default generator in Prisma ORM 7.0 and we recommend migrating to it as soon as possible. It has been Generally Available since v6.16.0.
A generator block accepts the following fields:
Name
Required
Type
Description
provider
Yes
prisma-client
Describes which generator to use. This can point to a file that implements a generator or specify a built-in generator directly.
output
Yes
String (file path)
Determines the location for the generated client, learn more.
previewFeatures
No
List of Enums
Use intellisense to see list of currently available Preview features (Ctrl+Space in Visual Studio Code) Default: none
Determines whether the generated code supports ESM (uses import) or CommonJS (uses require(...)) modules. We always recommend esm unless you have a good reason to use cjs. Default: Inferred from environment.
generatedFileExtension
No
Enum (ts or mts or cts)
File extension for generated TypeScript files. Default: ts
importFileExtension
No
Enum (ts,mts,cts,js,mjs,cjs, empty (for bare imports))
File extension used in import statements Default: Inferred from environment.
Note that the above generator definition is equivalent to the following because it uses the default values for output, engineType and binaryTargets (and implicitly previewFeatures):
Model names must adhere to the following regular expression: [A-Za-z][A-Za-z0-9_]*
Model names must start with a letter and are typically spelled in PascalCase
Model names should use the singular form (for example, User instead of user, users or Users)
Prisma ORM has a number of reserved words that are being used by Prisma ORM internally and therefore cannot be used as a model name. You can find the reserved words here and here.
Note: You can use the @@map attribute to map a model (for example, User) to a table with a different name that does not match model naming conventions (for example, users).
In version 2.3.0 and later, introspection lists model fields in the same order as the corresponding columns in the database. Relation fields are listed after scalar fields.
The data source connector determines what native database type each of Prisma ORM scalar type maps to. Similarly, the generator determines what type in the target programming language each of these types map to.
Prisma models also have model field types that define relations between models.
TINYINT maps to Int if the max length is greater than 1 (for example, TINYINT(2)) or the default value is anything other than 1, 0, or NULL. TINYINT(1) maps to Boolean.
† p (precision), the maximum total number of decimal digits to be stored. s (scale), the number of decimal digits that are stored to the right of the decimal point.
† p (precision), the maximum total number of decimal digits to be stored. s (scale), the number of decimal digits that are stored to the right of the decimal point.
† p (precision), the maximum total number of decimal digits to be stored. s (scale), the number of decimal digits that are stored to the right of the decimal point.
PostgreSQL's money type is not yet supported by CockroachDB
† p (precision), the maximum total number of decimal digits to be stored. s (scale), the number of decimal digits that are stored to the right of the decimal point.
There currently is a bug that doesn't allow you to pass in DateTime values as strings and produces a runtime error when you do. DateTime values need to be passed as Date objects (i.e. new Date('2024-12-04') instead of '2024-12-04').
Not supported by MongoDB
The MongoDB connector does not support the Unsupported type.
The Unsupported type was introduced in 2.17.0 and allows you to represent data types in the Prisma schema that are not supported by Prisma Client. Fields of type Unsupported can be created during Introspection with prisma db pull or written by hand, and created in the database with Prisma Migrate or db push.
Fields with Unsupported types are not available in the generated client.
If a model contains a requiredUnsupported type, prisma.model.create(..), prisma.model.update(...) and prisma.model.upsert(...) are not available in Prisma Client.
When you introspect a database that contains unsupported types, Prisma ORM will provide the following warning:
*** WARNING ***These fields are not supported by Prisma Client, because Prisma does not currently support their types.* Model "Post", field: "circle", original data type: "circle"
model Star { id Int @id @default(autoincrement()) position Unsupported("circle")? example1 Unsupported("circle") circle Unsupported("circle")? @default(dbgenerated("'<(10,4),11>'::circle"))}
Scalar lists (arrays) are only supported in the data model if your database natively supports them. Currently, scalar lists are therefore only supported when using PostgreSQL or CockroachDB (since MySQL and SQLite don't natively support scalar lists).
In most cases, you want your database to create the ID. To do this, annotate the ID field with the @default attribute and initialize the field with a function.
In the following example, authorId is a both a relation scalar and the ID of Profile:
model Profile { authorId Int @id author User @relation(fields: [authorId], references: [id]) bio String}model User { id Int @id email String @unique name String? profile Profile?}
In this scenario, you cannot create a Profile only - you must use Prisma Client's nested writes create a Useror connect the profile to an existing user.
The following example creates a user and a profile:
const userWithProfile = await prisma.user.create({ data: { id: 3, email: "bob@prisma.io", name: "Bob Prismo", profile: { create: { bio: "Hello, I'm Bob Prismo and I love apples, blue nail varnish, and the sound of buzzing mosquitoes.", }, }, },});
The following example connects a new profile to a user:
const profileWithUser = await prisma.profile.create({ data: { bio: "Hello, I'm Bob and I like nothing at all. Just nothing.", author: { connect: { id: 22, }, }, },});
model Post { title String published Boolean @default(false) author User @relation(fields: [authorId], references: [id]) authorId Int @@id([authorId, title])}model User { id Int @default(autoincrement()) email String @unique name String? posts Post[]}
When creating new Post records, you now must provide a unique combination of values for authorId (foreign key) and title:
Default values that cannot yet be represented in the Prisma schema are represented by the dbgenerated() function when you use introspection.
Default values are not allowed on relation fields in the Prisma schema. Note however that you can still define default values on the fields backing a relation (the ones listed in the fields argument in the @relation attribute). A default value on the field backing a relation will mean that relation is populated automatically for you.
Default values can be used with scalar lists in databases that natively support them.
Default values are not allowed on relation fields in the Prisma schema. Note however that you can still define default values on the fields backing a relation (the ones listed in the fields argument in the @relation attribute). A default value on the field backing a relation will mean that relation is populated automatically for you.
Default values can be used with scalar lists in databases that natively support them.
JSON data. Note that JSON needs to be enclosed with double-quotes inside the @default attribute, e.g.: @default("[]"). If you want to provide a JSON object, you need to enclose it with double-quotes and then escape any internal double quotes using a backslash, e.g.: @default("{ \"hello\": \"world\" }").
model User { id Int @id @default(autoincrement()) email String @unique name String? role Role @default(USER) posts Post[] profile Profile?}
enum Role { USER ADMIN}
model User { id String @id @default(auto()) @map("_id") @db.ObjectId email String @unique name String? role Role @default(USER) posts Post[] profile Profile?}
model User { id Int @id @default(autoincrement()) posts Post[] favoriteColors String[] @default(["red", "yellow", "purple"]) roles Role[] @default([USER, DEVELOPER])}enum Role { USER DEVELOPER ADMIN}
model Post { author User @relation(fields: [authorId], references: [id]) authorId Int @unique title String published Boolean @default(false)}model User { id Int @id @default(autoincrement()) email String? @unique name String Post Post[]}
All fields that make up the unique constraint must be mandatory fields. The following model is not valid because id could be null:
model User { firstname Int lastname Int id Int? @@unique([firstname, lastname, id])}
The reason for this behavior is that all connectors consider null values to be distinct, which means that two rows that look identical are considered unique:
firstname | lastname | id -----------+----------+------ John | Smith | null John | Smith | null
model User { id Int @default(autoincrement()) firstName String lastName String isAdmin Boolean @default(false) @@unique([firstName, lastName, isAdmin])}
model Post { id Int @default(autoincrement()) author User @relation(fields: [authorId], references: [id]) authorId Int title String published Boolean @default(false) @@unique([authorId, title])}model User { id Int @id @default(autoincrement()) email String @unique posts Post[]}
model User { id Int @default(autoincrement()) firstName String lastName String isAdmin Boolean @default(false) @@unique(fields: [firstName, lastName, isAdmin], name: "admin_identifier")}
To retrieve a user, use the custom field name (admin_identifier):
In version 3.12.0 and later, you can define an index on a field of a composite type using the syntax @@index([compositeType.field]). See Defining composite type indexes for more details.
A list of field names - for example, ["firstname", "lastname"]
name
No
String
The name that Prisma Client will expose for the argument covering all fields, e.g. fullName in fullName: { firstName: "First", lastName: "Last"}
map
No
map
The name of the index in the underlying database (Prisma generates an index name that respects identifier length limits if you do not specify a name. Prisma uses the following naming convention: tablename.field1_field2_field3_unique)
length
No
number
Allows you to specify a maximum length for the subpart of the value to be indexed.
MySQL only. In preview in versions 3.5.0 and later, and in general availability in versions 4.0.0 and later.
sort
No
String
Allows you to specify in what order the entries of the index or constraint are stored in the database. The available options are asc and desc.
In preview in versions 3.5.0 and later, and in general availability in versions 4.0.0 and later.
clustered
No
Boolean
Defines whether the index is clustered or non-clustered. Defaults to false.
SQL Server only. In preview in versions 3.5.0 and later, and in general availability in versions 4.0.0 and later.
type
No
identifier
Allows you to specify an index access method. Defaults to BTree.
PostgreSQL and CockroachDB only. In preview with the Hash index access method in versions 3.6.0 and later, and with the Gist, Gin, SpGist and Brin methods added in 3.14.0. In general availability in versions 4.0.0 and later.
ops
No
identifier or a function
Allows you to define the index operators for certain index types.
PostgreSQL only. In preview in versions 3.14.0 and later, and in general availability in versions 4.0.0 and later.
The name of the fields argument on the @@index attribute can be omitted:
If your model's primary key is of type ObjectId in the underlying database, both the primary key and the foreign key must have the @db.ObjectId attribute
Maps a field name or enum value from the Prisma schema to a column or document field with a different name in the database. If you do not use @map, the Prisma field name matches the column name or document field name exactly.
In Prisma ORM v7 and later, the generated TypeScript enum uses the mapped values:
export const Role = { ADMIN: "admin", CUSTOMER: "CUSTOMER",} as const;
This means Role.ADMIN evaluates to "admin", not "ADMIN".
There is currently a known bug in Prisma ORM v7 where using mapped enum values with Prisma Client operations causes runtime errors. See the Prisma 7 upgrade guide for workarounds and details.
Maps the Prisma schema model name to a table (relational databases) or collection (MongoDB) with a different name, or an enum name to a different underlying enum in the database. If you do not use @@map, the model name matches the table (relational databases) or collection (MongoDB) name exactly.
Automatically stores the time when a record was last updated. If you do not supply a time yourself, Prisma Client will automatically set the value for fields with this attribute.
In versions before 4.4.0, if you're also using now(), the time might differ from the @updatedAt values if your database and app have different time zones. This happens because @updatedAt operates at the Prisma ORM level, while now() operates at the database level.
If you pass an empty update clause, the @updatedAt value will remain unchanged. For example:
Add @ignore to a field that you want to exclude from Prisma Client (for example, a field that you do not want Prisma Client users to update). Ignored fields are excluded from the generated Prisma Client. The model's create method is disabled when doing this for required fields with no @default (because the database cannot create an entry without that data).
Add @@ignore to a model that you want to exclude from Prisma Client (for example, a model that you do not want Prisma users to update). Ignored models are excluded from the generated Prisma Client.
In the following example, the Post model is invalid because it does not have a unique identifier. Use @@ignore to exclude it from the generated Prisma Client API:
schema.prisma
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.model Post { id Int @default(autoincrement()) // no unique identifier author User @relation(fields: [authorId], references: [id]) authorId Int @@ignore}
In the following example, the Post model is invalid because it does not have a unique identifier, and the posts relation field on User is invalid because it refers to the invalid Post model. Use @@ignore on the Post model and @ignore on the posts relation field in User to exclude both the model and the relation field from the generated Prisma Client API:
schema.prisma
/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.model Post { id Int @default(autoincrement()) // no unique identifier author User @relation(fields: [authorId], references: [id]) authorId Int @@ignore}model User { id Int @id @default(autoincrement()) name String? posts Post[] @ignore}
Add @@schema to a model to specify which schema in your database should contain the table associated with that model. Learn more about adding multiple schema's here.
Multiple database schema support is only available with the PostgreSQL, CockroachDB, and SQL Server connectors.
Not supported by MongoDB
The MongoDB connector does not support the autoincrement() function.
Create a sequence of integers in the underlying database and assign the incremented values to the ID values of the created records based on the sequence.
Compatible with Int on most databases (BigInt on CockroachDB)
Implemented on the database-level, meaning that it manifests in the database schema and can be recognized through introspection. Database implementations:
@default(sequence(virtual)) Virtual sequences are sequences that do not generate monotonically increasing values and instead produce values like those generated by the built-in function unique_rowid().
cache
@default(sequence(cache: 20)) The number of sequence values to cache in memory for reuse in the session. A cache size of 1 means that there is no cache, and cache sizes of less than 1 are not valid.
increment
@default(sequence(increment: 4)) The new value by which the sequence is incremented. A negative number creates a descending sequence. A positive number creates an ascending sequence.
minValue
@default(sequence(minValue: 10)) The new minimum value of the sequence.
maxValue
@default(sequence(maxValue: 3030303)) The new maximum value of the sequence.
start
@default(sequence(start: 2)) The value the sequence starts at, if it's restarted or if the sequence hits the maxValue.
Since the length of cuid() output is undefined per the cuid creator, a safe field size is 30 characters, in order to allow for enough characters for very large values. If you set the field size as less than 30, and then a larger value is generated by cuid(), you might see Prisma Client errors such as Error: The provided value for the column is too long for the column's type.
For MongoDB: cuid() does not generate a valid ObjectId. You can use @db.ObjectId syntax if you want to use ObjectId in the underlying database. However, you can still use cuid() if your _id field is not of type ObjectId.
For MongoDB: uuid() does not generate a valid ObjectId. You can use @db.ObjectId syntax if you want to use ObjectId in the underlying database. However, you can still use uuid() if your _id field is not of type ObjectId.
Generated values based on the Nano ID spec. nanoid() accepts an integer value between 2 and 255 that specifies the length of the generate ID value, e.g. nanoid(16) will generated ID with 16 characters. If you don't provide a value to the nanoid() function, the default value is 21.
Nano ID is quite comparable to UUID v4 (random-based). It has a similar number of random bits in the ID (126 in Nano ID and 122 in UUID), so it has a similar collision probability:
For there to be a one in a billion chance of duplication, 103 trillion version 4 IDs must be generated.
There are two main differences between Nano ID and UUID v4:
Nano ID uses a bigger alphabet, so a similar number of random bits are packed in just 21 symbols instead of 36.
Nano ID code is 4 times smaller than uuid/v4 package: 130 bytes instead of 423.
For MongoDB: nanoid() does not generate a valid ObjectId. You can use @db.ObjectId syntax if you want to use ObjectId in the underlying database. However, you can still use nanoid() if your _id field is not of type ObjectId.
In versions before 4.4.0, if you're also using @updatedAt, the time might differ from the now() values if your database and app have different time zones. This happens because @updatedAt operates at the Prisma ORM level, while now() operates at the database level.
Implemented on the database-level, meaning that it manifests in the database schema and can be recognized through introspection. Database implementations:
String values in dbgenerated(...) might not match what the DB returns as the default value, because values such as strings may be explicitly cast (e.g. 'hello'::STRING). When a mismatch is present, Prisma Migrate indicates a migration is still needed. You can use prisma db pull to infer the correct value to resolve the discrepancy. (Related issue)
You can also use dbgenerated(...) to set the default value for supported types. For example, in PostgreSQL you can generate UUIDs at the database level rather than rely on Prisma ORM's uuid():
model User { id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid id String @id @default(uuid()) @db.Uuid test String?}