apps/docs/content/docs.v6/orm/reference/prisma-schema-reference.mdx
datasourceDefines a data source in the Prisma schema.
A datasource block accepts the following fields:
| Name | Required | Type | Description |
|---|---|---|---|
provider | Yes | String (postgresql, mysql, sqlite, sqlserver, mongodb, cockroachdb) | Describes which data source connectors to use. |
url | Yes | String (URL) | 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. |
| extensions | No | List of strings (PostgreSQL extension names) | Allows you to represent PostgreSQL extensions in your schema. Available in preview for PostgreSQL only in Prisma ORM versions 4.5.0 and later. |
::::note
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.
::::
The following providers are available:
datasource block in a schema.datasource db is convention - however, you can give your data source any name - for example, datasource mysql or datasource data.In this example, the target database is available with the following credentials:
johndoemypasswordlocalhost5432mydbpublicdatasource db {
provider = "postgresql"
url = "postgresql://johndoe:mypassword@localhost:5432/mydb?schema=public"
}
Learn more about PostgreSQL connection strings here.
In this example, the target database is available with the following credentials:
johndoemypasswordlocalhost5432mydbpublicdatasource 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.
DATABASE_URL=postgresql://johndoe:mypassword@localhost:5432/mydb?schema=public
In this example, the target database is available with the following credentials:
johndoemypasswordlocalhost3306mydbdatasource db {
provider = "mysql"
url = "mysql://johndoe:mypassword@localhost:3306/mydb"
}
Learn more about MySQL connection strings here.
rootpasswordcluster1.test1.mongodb.nettestingdatasource db {
provider = "mongodb"
url = "mongodb+srv://root:[email protected]/testing?retryWrites=true&w=majority"
}
Learn more about MongoDB connection strings here.
In this example, the target database is located in a file called dev.db:
datasource db {
provider = "sqlite"
url = "file:./dev.db"
}
Learn more about SQLite connection strings here.
In this example, the target database is available with the following credentials:
johndoemypasswordlocalhost26257mydbpublicdatasource db {
provider = "cockroachdb"
url = "postgresql://johndoe:mypassword@localhost:26257/mydb?schema=public"
}
The format for connection strings is the same as for PostgreSQL. Learn more about PostgreSQL connection strings here.
generatorDefines a generator in the Prisma schema.
prisma-client-js providerThis 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. |
:::note[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.
:::
prisma-client providerThe 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.
:::note
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 |
runtime | No | Enum (nodejs, deno, bun, workerd (alias cloudflare), vercel-edge (alias edge-light), react-native) | Target runtime environment. Default: nodejs |
moduleFormat | No | Enum (esm or cjs) | 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. |
binaryTargets optionsThe following tables list all supported operating systems with the name of platform to specify in binaryTargets.
Unless specified otherwise, the default supported CPU architecture is x86_64.
| Build OS | Prisma engine build name |
|---|---|
| macOS Intel x86_64 | darwin |
| macOS ARM64 | darwin-arm64 |
| Build OS | Prisma engine build name |
|---|---|
| Windows | windows |
| Build OS | Prisma engine build name | OpenSSL |
|---|---|---|
| Alpine (3.17 and newer) | linux-musl-openssl-3.0.x* | 3.0.x |
| Alpine (3.16 and older) | linux-musl | 1.1.x |
* Available in Prisma ORM versions 4.8.0 and later.
| Build OS | Prisma engine build name | OpenSSL |
|---|---|---|
| Alpine (3.17 and newer) | linux-musl-arm64-openssl-3.0.x* | 3.0.x |
| Alpine (3.16 and older) | linux-musl-arm64-openssl-1.1.x* | 1.1.x |
* Available in Prisma ORM versions 4.10.0 and later.
| Build OS | Prisma engine build name | OpenSSL |
|---|---|---|
| Debian 8 (Jessie) | debian-openssl-1.0.x | 1.0.x |
| Debian 9 (Stretch) | debian-openssl-1.1.x | 1.1.x |
| Debian 10 (Buster) | debian-openssl-1.1.x | 1.1.x |
| Debian 11 (Bullseye) | debian-openssl-1.1.x | 1.1.x |
| Debian 12 (Bookworm) | debian-openssl-3.0.x | 3.0.x |
| Build OS | Prisma engine build name | OpenSSL |
|---|---|---|
| Ubuntu 14.04 (trusty) | debian-openssl-1.0.x | 1.0.x |
| Ubuntu 16.04 (xenial) | debian-openssl-1.0.x | 1.0.x |
| Ubuntu 18.04 (bionic) | debian-openssl-1.1.x | 1.1.x |
| Ubuntu 19.04 (disco) | debian-openssl-1.1.x | 1.1.x |
| Ubuntu 20.04 (focal) | debian-openssl-1.1.x | 1.1.x |
| Ubuntu 21.04 (hirsute) | debian-openssl-1.1.x | 1.1.x |
| Ubuntu 22.04 (jammy) | debian-openssl-3.0.x | 3.0.x |
| Ubuntu 23.04 (lunar) | debian-openssl-3.0.x | 3.0.x |
| Build OS | Prisma engine build name | OpenSSL |
|---|---|---|
| CentOS 7 | rhel-openssl-1.0.x | 1.0.x |
| CentOS 8 | rhel-openssl-1.1.x | 1.1.x |
| Build OS | Prisma engine build name | OpenSSL |
|---|---|---|
| Fedora 28 | rhel-openssl-1.1.x | 1.1.x |
| Fedora 29 | rhel-openssl-1.1.x | 1.1.x |
| Fedora 30 | rhel-openssl-1.1.x | 1.1.x |
| Fedora 36 | rhel-openssl-3.0.x | 3.0.x |
| Fedora 37 | rhel-openssl-3.0.x | 3.0.x |
| Fedora 38 | rhel-openssl-3.0.x | 3.0.x |
| Build OS | Prisma engine build name | OpenSSL |
|---|---|---|
| Linux Mint 18 | debian-openssl-1.0.x | 1.0.x |
| Linux Mint 19 | debian-openssl-1.1.x | 1.1.x |
| Linux Mint 20 | debian-openssl-1.1.x | 1.1.x |
| Linux Mint 21 | debian-openssl-3.0.x | 3.0.x |
| Build OS | Prisma engine build name | OpenSSL |
|---|---|---|
| Arch Linux 2019.09.01 | debian-openssl-1.1.x | 1.1.x |
| Arch Linux 2023.04.23 | debian-openssl-3.0.x | 3.0.x |
| Build OS | Prisma engine build name | OpenSSL |
|---|---|---|
| Linux ARM64 glibc-based distro | linux-arm64-openssl-1.0.x | 1.0.x |
| Linux ARM64 glibc-based distro | linux-arm64-openssl-1.1.x | 1.1.x |
| Linux ARM64 glibc-based distro | linux-arm64-openssl-3.0.x | 3.0.x |
prisma-client-js generator with the default output, previewFeatures, engineType and binaryTargetsgenerator client {
provider = "prisma-client-js"
}
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):
generator client {
provider = "prisma-client-js"
output = "node_modules/.prisma/client"
engineType = "library"
binaryTargets = ["native"]
}
output location for Prisma ClientThis example shows how to define a custom output location of the generated asset to override the default one.
generator client {
provider = "prisma-client-js"
output = "../src/generated/client"
}
binaryTargets to ensure compatibility with the OSThis example shows how to configure Prisma Client to run on Ubuntu 19.04 (disco) based on the table above.
generator client {
provider = "prisma-client-js"
binaryTargets = ["debian-openssl-1.1.x"]
}
provider pointing to some custom generator implementationThis example shows how to use a custom generator that's located in a directory called my-generator.
generator client {
provider = "./my-generator"
}
modelDefines a Prisma model .
[A-Za-z][A-Za-z0-9_]*User instead of user, users or Users)Note: You can use the
@@mapattribute to map a model (for example,User) to a table with a different name that does not match model naming conventions (for example,users).
User with two scalar fieldsmodel User {
email String @unique // `email` can not be optional because it's the only unique field on the model
name String?
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
email String @unique
name String?
}
model fieldsFields are properties of models.
[A-Za-z][A-Za-z0-9_]*Note: You can use the
@mapattribute to map a field name to a column with a different name that does not match field naming conventions: e.g.myField @map("my_field").
model field scalar typesThe 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.
StringVariable length text.
| Connector | Default mapping |
|---|---|
| PostgreSQL | text |
| SQL Server | nvarchar(1000) |
| MySQL | varchar(191) |
| MongoDB | String |
| SQLite | TEXT |
| CockroachDB | STRING |
| Native database type | Native database type attribute | Notes |
|---|---|---|
text | @db.Text | |
char(x) | @db.Char(x) | |
varchar(x) | @db.VarChar(x) | |
bit(x) | @db.Bit(x) | |
varbit | @db.VarBit | |
uuid | @db.Uuid | |
xml | @db.Xml | |
inet | @db.Inet | |
citext | @db.Citext | Only available if Citext extension is enabled. |
| Native database type | Native database type attribute |
|---|---|
VARCHAR(x) | @db.VarChar(x) |
TEXT | @db.Text |
CHAR(x) | @db.Char(x) |
TINYTEXT | @db.TinyText |
MEDIUMTEXT | @db.MediumText |
LONGTEXT | @db.LongText |
You can use Prisma Migrate to map @db.Bit(1) to String:
model Model {
/* ... */
myField String @db.Bit(1)
}
String
| Native database type attribute | Notes |
|---|---|
@db.String | |
@db.ObjectId | Required if the underlying BSON type is OBJECT_ID (ID fields, relation scalars) |
| Native database type | Native database type attribute |
|---|---|
char(x) | @db.Char(x) |
nchar(x) | @db.NChar(x) |
varchar(x) | @db.VarChar(x) |
nvarchar(x) | @db.NVarChar(x) |
text | @db.Text |
ntext | @db.NText |
xml | @db.Xml |
uniqueidentifier | @db.UniqueIdentifier |
TEXT
| Native database type | Native database type attribute | Notes |
|---|---|---|
STRING(x) | TEXT(x) | VARCHAR(x) | @db.String(x) | |
CHAR(x) | @db.Char(x) | |
"char" | @db.CatalogSingleChar | |
BIT(x) | @db.Bit(x) | |
VARBIT | @db.VarBit | |
UUID | @db.Uuid | |
INET | @db.Inet |
Note that the xml and citext types supported in PostgreSQL are not currently supported in CockroachDB.
| Prisma Client JS |
|---|
string |
BooleanTrue or false value.
| Connector | Default mapping |
|---|---|
| PostgreSQL | boolean |
| SQL Server | bit |
| MySQL | TINYINT(1) |
| MongoDB | Bool |
| SQLite | INTEGER |
| CockroachDB | BOOL |
| Native database types | Native database type attribute | Notes |
|---|---|---|
boolean | @db.Boolean |
| Native database types | Native database type attribute | Notes |
|---|---|---|
TINYINT(1) | @db.TinyInt(1) | 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 |
BIT(1) | @db.Bit |
Bool
| Native database types | Native database type attribute | Notes |
|---|---|---|
bit | @db.Bit |
INTEGER
| Native database types | Native database type attribute | Notes |
|---|---|---|
BOOL | @db.Bool |
| Prisma Client JS |
|---|
boolean |
Int| Connector | Default mapping |
|---|---|
| PostgreSQL | integer |
| SQL Server | int |
| MySQL | INT |
| MongoDB | Int |
| SQLite | INTEGER |
| CockroachDB | INT |
| Native database types | Native database type attribute | Notes |
|---|---|---|
integer | int, int4 | @db.Integer | |
smallint | int2 | @db.SmallInt | |
smallserial | serial2 | @db.SmallInt @default(autoincrement()) | |
serial | serial4 | @db.Int @default(autoincrement()) | |
oid | @db.Oid |
| Native database types | Native database type attribute | Notes |
|---|---|---|
INT | @db.Int | |
INT UNSIGNED | @db.UnsignedInt | |
SMALLINT | @db.SmallInt | |
SMALLINT UNSIGNED | @db.UnsignedSmallInt | |
MEDIUMINT | @db.MediumInt | |
MEDIUMINT UNSIGNED | @db.UnsignedMediumInt | |
TINYINT | @db.TinyInt | 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. |
TINYINT UNSIGNED | @db.UnsignedTinyInt | TINYINT(1) UNSIGNED maps to Int, not Boolean |
YEAR | @db.Year |
Int
| Native database type attribute | Notes |
|---|---|
@db.Int | |
@db.Long |
| Native database types | Native database type attribute | Notes |
|---|---|---|
int | @db.Int | |
smallint | @db.SmallInt | |
tinyint | @db.TinyInt | |
bit | @db.Bit |
INTEGER
| Native database types | Native database type attribute | Notes |
|---|---|---|
INTEGER | INT | INT8 | @db.Int8 | Note that this differs from PostgreSQL, where integer and int are aliases for int4 and map to @db.Integer |
INT4 | @db.Int4 | |
INT2 | SMALLINT | @db.Int2 | |
SMALLSERIAL | SERIAL2 | @db.Int2 @default(autoincrement()) | |
SERIAL | SERIAL4 | @db.Int4 @default(autoincrement()) | |
SERIAL8 | BIGSERIAL | @db.Int8 @default(autoincrement()) |
| Prisma Client JS |
|---|
number |
BigIntBigInt is available in version 2.17.0 and later.
| Connector | Default mapping |
|---|---|
| PostgreSQL | bigint |
| SQL Server | int |
| MySQL | BIGINT |
| MongoDB | Long |
| SQLite | INTEGER |
| CockroachDB | INTEGER |
| Native database types | Native database type attribute | Notes |
|---|---|---|
bigint | int8 | @db.BigInt | |
bigserial | serial8 | @db.BigInt @default(autoincrement()) |
| Native database types | Native database type attribute | Notes |
|---|---|---|
BIGINT | @db.BigInt | |
SERIAL | @db.UnsignedBigInt @default(autoincrement()) |
Long
| Native database types | Native database type attribute | Notes |
|---|---|---|
bigint | @db.BigInt |
INTEGER
| Native database types | Native database type attribute | Notes |
|---|---|---|
BIGINT | INT | INT8 | @db.Int8 | Note that this differs from PostgreSQL, where int is an alias for int4 |
bigserial | serial8 | @db.Int8 @default(autoincrement()) |
| Client | Type | Description |
|---|---|---|
| Prisma Client JS | BigInt | See examples of working with BigInt |
FloatFloating point number.
Floatmaps toDoublein 2.17.0 and later - see release notes and Video: Changes to the default mapping of Float in Prisma ORM 2.17.0 for more information about this change.
| Connector | Default mapping |
|---|---|
| PostgreSQL | double precision |
| SQL Server | float(53) |
| MySQL | DOUBLE |
| MongoDB | Double |
| SQLite | REAL |
| CockroachDB | DOUBLE PRECISION |
| Native database types | Native database type attribute | Notes |
|---|---|---|
double precision | @db.DoublePrecision | |
real | @db.Real |
| Native database types | Native database type attribute | Notes |
|---|---|---|
FLOAT | @db.Float | |
DOUBLE | @db.Double |
Double
| Native database types | Native database type attribute |
|---|---|
float | @db.Float |
money | @db.Money |
smallmoney | @db.SmallMoney |
real | @db.Real |
REAL
| Native database types | Native database type attribute | Notes |
|---|---|---|
DOUBLE PRECISION | FLOAT8 | @db.Float8 | |
REAL | FLOAT4 | FLOAT | @db.Float4 |
| Prisma Client JS |
|---|
number |
Decimal| Connector | Default mapping |
|---|---|
| PostgreSQL | decimal(65,30) |
| SQL Server | decimal(32,16) |
| MySQL | DECIMAL(65,30) |
| MongoDB | Not supported |
| SQLite | DECIMAL |
| CockroachDB | DECIMAL |
| Native database types | Native database type attribute | Notes |
|---|---|---|
decimal | numeric | @db.Decimal(p, s)† | |
money | @db.Money |
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.| Native database types | Native database type attribute | Notes |
|---|---|---|
DECIMAL | NUMERIC | @db.Decimal(p, s)† |
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.| Native database types | Native database type attribute | Notes |
|---|---|---|
decimal | numeric | @db.Decimal(p, s)† |
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.DECIMAL (changed from REAL in 2.17.0)
| Native database types | Native database type attribute | Notes |
|---|---|---|
DECIMAL | DEC | NUMERIC | @db.Decimal(p, s)† | |
money | Not yet | 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.| Client | Type | Description |
|---|---|---|
| Prisma Client JS | Decimal | See examples of working with Decimal |
DateTimeDateTime as native Date objects.0000-00-00 00:00:00, 0000-00-00, 00:00:00) in MySQL.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').You can find more info and examples in this section: Working with DateTime.
| Connector | Default mapping |
|---|---|
| PostgreSQL | timestamp(3) |
| SQL Server | datetime2 |
| MySQL | DATETIME(3) |
| MongoDB | Timestamp |
| SQLite | NUMERIC |
| CockroachDB | TIMESTAMP |
| Native database types | Native database type attribute | Notes |
|---|---|---|
timestamp(x) | @db.Timestamp(x) | |
timestamptz(x) | @db.Timestamptz(x) | |
date | @db.Date | |
time(x) | @db.Time(x) | |
timetz(x) | @db.Timetz(x) |
| Native database types | Native database type attribute | Notes |
|---|---|---|
DATETIME(x) | @db.DateTime(x) | |
DATE(x) | @db.Date(x) | |
TIME(x) | @db.Time(x) | |
TIMESTAMP(x) | @db.Timestamp(x) |
You can also use MySQL's YEAR type with Int:
yearField Int @db.Year
Timestamp
| Native database types | Native database type attribute | Notes |
|---|---|---|
date | @db.Date | |
time | @db.Time | |
datetime | @db.DateTime | |
datetime2 | @db.DateTime2 | |
smalldatetime | @db.SmallDateTime | |
datetimeoffset | @db.DateTimeOffset |
NUMERIC or STRING. If the underlying data type is STRING, you must use one of the following formats:
| Native database types | Native database type attribute | Notes |
|---|---|---|
TIMESTAMP(x) | @db.Timestamp(x) | |
TIMESTAMPTZ(x) | @db.Timestamptz(x) | |
DATE | @db.Date | |
TIME(x) | @db.Time(x) | |
TIMETZ(x) | @db.Timetz(x) |
| Prisma Client JS |
|---|
Date |
JsonA JSON object.
| Connector | Default mapping |
|---|---|
| PostgreSQL | jsonb |
| SQL Server | Not supported |
| MySQL | JSON |
| MongoDB | A valid BSON object (Relaxed mode) |
| SQLite | JSONB |
| CockroachDB | JSONB |
| Native database types | Native database type attribute | Notes |
|---|---|---|
json | @db.Json | |
jsonb | @db.JsonB |
| Native database types | Native database type attribute | Notes |
|---|---|---|
JSON | @db.Json |
A valid BSON object (Relaxed mode)
Microsoft SQL Server does not have a specific data type for JSON. However, there are a number of built-in functions for reading and modifying JSON.
Not supported
| Native database types | Native database type attribute | Notes |
|---|---|---|
JSON | JSONB | @db.JsonB |
| Prisma Client JS |
|---|
object |
BytesBytes is available in version 2.17.0 and later.
| Connector | Default mapping |
|---|---|
| PostgreSQL | bytea |
| SQL Server | varbinary |
| MySQL | LONGBLOB |
| MongoDB | BinData |
| SQLite | BLOB |
| CockroachDB | BYTES |
| Native database types | Native database type attribute |
|---|---|
bytea | @db.ByteA |
| Native database types | Native database type attribute | Notes |
|---|---|---|
LONGBLOB | @db.LongBlob | |
BINARY | @db.Binary | |
VARBINARY | @db.VarBinary | |
TINYBLOB | @db.TinyBlob | |
BLOB | @db.Blob | |
MEDIUMBLOB | @db.MediumBlob | |
BIT | @db.Bit |
BinData
| Native database type attribute | Notes |
|---|---|
@db.ObjectId | Required if the underlying BSON type is OBJECT_ID (ID fields, relation scalars) |
@db.BinData |
| Native database types | Native database type attribute | Notes |
|---|---|---|
binary | @db.Binary | |
varbinary | @db.VarBinary | |
image | @db.Image |
BLOB
| Native database types | Native database type attribute |
|---|---|
BYTES | BYTEA | BLOB | @db.Bytes |
| Client | Type | Description |
|---|---|---|
| Prisma Client JS | Uint8Array | See examples of working with Bytes |
| Prisma Client JS (before v6) | Buffer | See examples of working with Bytes |
Unsupported:::warning
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 required Unsupported 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"))
}
model field type modifiers[] modifierMakes a field a list.
Post[]?).model User {
id Int @id @default(autoincrement())
favoriteColors String[] // [!code highlight]
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
favoriteColors String[] // [!code highlight]
}
Available in version 4.0.0 and later.
model User {
id Int @id @default(autoincrement())
favoriteColors String[] @default(["red", "blue", "green"]) // [!code highlight]
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
favoriteColors String[] @default(["red", "blue", "green"]) // [!code highlight]
}
? modifierMakes a field optional.
Posts[])name fieldmodel User {
id Int @id @default(autoincrement())
name String? // [!code highlight]
}
Attributes modify the behavior of a field or block (e.g. models). There are two ways to add attributes to your data model:
@@@Some attributes take arguments. Arguments in attributes are always named, but in most cases the argument name can be omitted.
Note: The leading underscore in a signature means the argument name can be omitted.
@idDefines a single-field ID on the model.
Corresponding database construct: PRIMARY KEY
Can be annotated with a @default attribute that uses functions to auto-generate an ID:
Can be defined on any scalar field (String, Int, enum)
Corresponding database construct: Any valid BSON type, except arrays
Every model must define an @id field
The underlying ID field name is always _id, and must be mapped with @map("_id")
Can be defined on any scalar field (String, Int, enum) unless you want to use ObjectId in your database
To use an ObjectId as your ID, you must:
Use the String or Bytes field type
Annotate your field with @db.ObjectId:
id String @db.ObjectId @map("_id")
Optionally, annotate your field with a @default attribute that uses the auto() function to auto-generate an ObjectId
id String @db.ObjectId @map("_id") @default(auto())
cuid(), uuid() and ulid() are supported but do not generate a valid ObjectId - use auto() instead for @id
autoincrement() is not supported
| Name | Required | Type | Description |
|---|---|---|---|
map | No | String | The name of the underlying primary key constraint in the database. |
Not supported for MySQL or MongoDB. |
| 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 ID are stored in the database. The available options are Asc and Desc.
SQL Server only. 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 ID is clustered or non-clustered. Defaults to true.
SQL Server only. In preview in versions 3.13.0 and later, and in general availability in versions 4.0.0 and later. |
@id(map: String?, length: number?, sort: String?, clustered: Boolean?)
Note: Before version 4.0.0, or 3.5.0 with the
extendedIndexesPreview feature enabled, the signature was:prisma@id(map: String?)
Note: Before version 3.0.0, the signature was:
prisma@id
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.
model User {
id Int @id @default(autoincrement())
name String
}
ObjectId as IDs (MongoDB only)model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
}
cuid() values as IDsmodel User {
id String @id @default(cuid())
name String
}
model User {
id String @id @default(cuid()) @map("_id")
name String
}
:::warning
You cannot use cuid() to generate a default value if your id field is of type ObjectId. Use the following syntax to generate a valid ObjectId:
id String @id @default(auto()) @db.ObjectId @map("_id")
:::
uuid() values as IDsmodel User {
id String @id @default(uuid())
name String
}
model User {
id String @id @default(uuid()) @map("_id")
name String
}
:::warning
You cannot use uuid() to generate a default value if your id field is of type ObjectId. Use the following syntax to generate a valid ObjectId:
id String @id @default(auto()) @db.ObjectId @map("_id")
:::
ulid() values as IDsmodel User {
id String @id @default(ulid())
name String
}
model User {
id String @id @default(ulid()) @map("_id")
name String
}
:::warning
You cannot use ulid() to generate a default value if your id field is of type ObjectId. Use the following syntax to generate a valid ObjectId:
id String @id @default(auto()) @db.ObjectId @map("_id")
:::
In the following example, id does not have a default value:
model User {
id String @id
name String
}
model User {
id String @id @map("_id") @db.ObjectId
name String
}
model User {
id String @id @map("_id")
name String
}
Note that in the above case, you must provide your own ID values when creating new records for the User model using Prisma Client, e.g.:
const newUser = await prisma.user.create({
data: {
id: 1,
name: "Alice",
},
});
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?
}
model Profile {
authorId String @id @map("_id") @db.ObjectId
author User @relation(fields: [authorId], references: [id])
bio String
}
model User {
id String @id @map("_id") @db.ObjectId
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 User or 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: "[email protected]",
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,
},
},
},
});
@@id:::warning
Not supported by MongoDB
The MongoDB connector does not support composite IDs.
:::
Defines a multi-field ID (composite ID) on the model.
PRIMARY KEY@default attribute that uses functions to auto-generate an IDString, Int, enum)field1_field2_field3| Name | Required | Type | Description |
|---|---|---|---|
fields | Yes | FieldReference[] | 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 | String | The name of the underlying primary key constraint in the database. |
Not supported for MySQL. |
| 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 ID are stored in the database. The available options are Asc and Desc.
SQL Server only. 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 ID is clustered or non-clustered. Defaults to true.
SQL Server only. In preview in versions 3.13.0 and later, and in general availability in versions 4.0.0 and later. |
The name of the fields argument on the @@id attribute can be omitted:
@@id(fields: [title, author])
@@id([title, author])
@@id(_ fields: FieldReference[], name: String?, map: String?)
Note: Until version 3.0.0, the signature was:
prisma@@id(_ fields: FieldReference[])
String fields (Relational databases only)model User {
firstName String
lastName String
email String @unique
isAdmin Boolean @default(false)
@@id([firstName, lastName])
}
When you create a user, you must provide a unique combination of firstName and lastName:
const user = await prisma.user.create({
data: {
firstName: "Alice",
lastName: "Smith",
},
});
To retrieve a user, use the generated composite ID field (firstName_lastName):
const user = await prisma.user.findUnique({
where: {
firstName_lastName: {
firstName: "Alice",
lastName: "Smith",
},
},
});
String fields and one Boolean field (Relational databases only)model User {
firstName String
lastName String
email String @unique
isAdmin Boolean @default(false)
@@id([firstName, lastName, isAdmin])
}
When creating new User records, you now must provide a unique combination of values for firstName, lastName and isAdmin:
const user = await prisma.user.create({
data: {
firstName: "Alice",
lastName: "Smith",
isAdmin: true,
},
});
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:
const post = await prisma.post.create({
data: {
title: "Hello World",
author: {
connect: {
email: "[email protected]",
},
},
},
});
@defaultDefines a default value for a field.
dbgenerated() function when you use introspection.fields argument in the @relation attribute). A default value on the field backing a relation will mean that relation is populated automatically for you.DEFAULT4, "hello") or one of the following functions:
autoincrement()sequence() (CockroachDB only)dbgenerated(...)cuid()cuid(2)uuid()uuid(4)uuid(7)ulid()nanoid()now()dbgenerated(...) function when you use introspection.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 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\" }").4, "hello") or one of the following functions:
| Name | Required | Type | Description |
|---|---|---|---|
value | Yes | An expression (e.g. 5, true, now()) | |
map | No | String | SQL Server only. |
The name of the value argument on the @default attribute can be omitted:
id Int @id @default(value: autoincrement())
id Int @id @default(autoincrement())
@default(_ value: Expression, map: String?)
Note: Until version 3.0.0, the signature was:
prisma@default(_ value: Expression)
Intmodel User {
email String @unique
profileViews Int @default(0)
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
profileViews Int @default(0)
}
Floatmodel User {
email String @unique
number Float @default(1.1)
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
number Float @default(1.1)
}
Decimalmodel User {
email String @unique
number Decimal @default(22.99)
}
[Not supported](https://github.com/prisma/prisma/issues/12637).
BigIntmodel User {
email String @unique
number BigInt @default(34534535435353)
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
number BigInt @default(34534535435353)
}
Stringmodel User {
email String @unique
name String @default("")
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
name String @default("")
}
Booleanmodel User {
email String @unique
isAdmin Boolean @default(false)
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
isAdmin Boolean @default(false)
}
DateTimeNote that static default values for DateTime are based on the ISO 8601 standard.
model User {
email String @unique
data DateTime @default("2020-03-19T14:21:00+02:00")
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
data DateTime @default("2020-03-19T14:21:00+02:00")
}
Bytesmodel User {
email String @unique
secret Bytes @default("SGVsbG8gd29ybGQ=")
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
secret Bytes @default("SGVsbG8gd29ybGQ=")
}
enumenum Role {
USER
ADMIN
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
role Role @default(USER) // [!code highlight]
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) // [!code highlight]
posts Post[]
profile Profile?
}
model User {
id Int @id @default(autoincrement())
posts Post[]
favoriteColors String[] @default(["red", "yellow", "purple"]) // [!code highlight]
roles Role[] @default([USER, DEVELOPER])
}
enum Role {
USER
DEVELOPER
ADMIN
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
posts Post[]
favoriteColors String[] @default(["red", "yellow", "purple"]) // [!code highlight]
roles Role[] @default([USER, DEVELOPER])
}
enum Role {
USER
DEVELOPER
ADMIN
}
@uniqueDefines a unique constraint for this field.
@unique can be optional or required@unique must be required if it represents the only unique constraint on a model without an @id / @@idUNIQUENULL values are considered to be distinct (multiple rows with NULL values in the same column are allowed)| Name | Required | Type | Description |
|---|---|---|---|
map | No | String | |
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 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 constraint is clustered or non-clustered. Defaults to false.
SQL Server only. In preview in versions 3.13.0 and later, and in general availability in versions 4.0.0 and later. |
@unique(map: String?, length: number?, sort: String?)
Note: Before version 4.0.0, or 3.5.0 with the
extendedIndexesPreview feature enabled, the signature was:prisma@unique(map: String?)
Note: Before version 3.0.0, the signature was:
text@unique
String fieldmodel User {
email String @unique
name String
}
model User {
id String @default(auto()) @map("_id") @db.ObjectId
name String
}
String fieldmodel User {
id Int @id @default(autoincrement())
email String? @unique
name String
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String? @unique
name String
}
authorIdmodel 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[]
}
model Post {
author User @relation(fields: [authorId], references: [id])
authorId String @unique @db.ObjectId
title String
published Boolean @default(false)
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String? @unique
name String
Post Post[]
}
cuid() values as default valuesmodel User {
token String @unique @default(cuid())
name String
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
token String @unique @default(cuid())
name String
}
@@uniqueDefines a compound unique constraint for the specified fields.
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
A model can have any number of @@unique blocks
UNIQUE@@unique block is required if it represents the only unique constraint on a model without an @id / @@id@@unique block cannot be used as the only unique identifier for a model - MongoDB requires an @id field| Name | Required | Type | Description |
|---|---|---|---|
fields | Yes | FieldReference[] | A list of field names - for example, ["firstname", "lastname"]. Fields must be mandatory - see remarks. |
name | No | String | The name of the unique combination of fields - defaults to fieldName1_fieldName2_fieldName3 |
map | No | String | |
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 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 constraint is clustered or non-clustered. Defaults to false.
SQL Server only. In preview in versions 3.13.0 and later, and in general availability in versions 4.0.0 and later. |
The name of the fields argument on the @@unique attribute can be omitted:
@@unique(fields: [title, author])
@@unique([title, author])
@@unique(fields: [title, author], name: "titleAuthor")
The length and sort arguments are added to the relevant field names:
@@unique(fields: [title(length:10), author])
@@unique([title(sort: Desc), author(sort: Asc)])
prisma@@unique(_ fields: FieldReference[], name: String?, map: String?)
Note: Before version 4.0.0, or before version 3.5.0 with the
extendedIndexesPreview feature enabled, the signature was:prisma@@unique(_ fields: FieldReference[], name: String?, map: String?)
Note: Before version 3.0.0, the signature was:
prisma@@unique(_ fields: FieldReference[], name: String?)
String fieldsmodel User {
id Int @default(autoincrement())
firstName String
lastName String
isAdmin Boolean @default(false)
@@unique([firstName, lastName])
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
firstName String
lastName String
isAdmin Boolean @default(false)
@@unique([firstName, lastName])
}
To retrieve a user, use the generated field name (firstname_lastname):
const user = await prisma.user.findUnique({
where: {
firstName_lastName: {
firstName: "Alice",
lastName: "Smith",
isAdmin: true,
},
},
});
String fields and one Boolean fieldmodel User {
id Int @default(autoincrement())
firstName String
lastName String
isAdmin Boolean @default(false)
@@unique([firstName, lastName, isAdmin])
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
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 Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
author User @relation(fields: [authorId], references: [id])
authorId String @db.ObjectId
title String
published Boolean @default(false)
@@unique([authorId, title])
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
email String @unique
posts Post[]
}
name for a multi-field unique attributemodel User {
id Int @default(autoincrement())
firstName String
lastName String
isAdmin Boolean @default(false)
@@unique(fields: [firstName, lastName, isAdmin], name: "admin_identifier")
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
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):
const user = await prisma.user.findUnique({
where: {
admin_identifier: {
firstName: "Alice",
lastName: "Smith",
isAdmin: true,
},
},
});
@@indexDefines an index in the database.
INDEXCREATE INDEX title ON public."Post"((lower(title)) text_ops);)WHERECONCURRENTLY:::info
While you cannot configure these option in your Prisma schema, you can still configure them on the database-level directly.
:::
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.| Name | Required | Type | Description |
|---|---|---|---|
fields | Yes | FieldReference[] | 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:
@@index(fields: [title, author])
@@index([title, author])
The length and sort arguments are added to the relevant field names:
@@index(fields: [title(length:10), author])
@@index([title(sort: Asc), author(sort: Desc)])
@@index(_ fields: FieldReference[], map: String?)
Note: Until version 3.0.0, the signature was:
prisma@@index(_ fields: FieldReference[], name: String?)The old
nameargument will still be accepted to avoid a breaking change.
Assume you want to add an index for the title field of the Post model
model Post {
id Int @id @default(autoincrement())
title String
content String?
@@index([title])
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
@@index([title, content])
}
model Post {
id Int @id @default(autoincrement())
title String
content String?
@@index(fields: [title, content], name: "main_index")
}
type Address {
street String
number Int
}
model User {
id Int @id
email String
address Address
@@index([address.number])
}
@relationDefines meta information about the relation. Learn more.
FOREIGN KEY / REFERENCESObjectId in the underlying database, both the primary key and the foreign key must have the @db.ObjectId attribute| Name | Type | Required | Description | Example |
|---|---|---|---|---|
name | String | Sometimes (e.g. to disambiguate a relation) | Defines the name of the relationship. In an m-n-relation, it also determines the name of the underlying relation table. | "CategoryOnPost", "MyRelation" |
fields | FieldReference[] | On annotated relation fields | A list of fields of the current model | ["authorId"], ["authorFirstName, authorLastName"] |
references | FieldReference[] | On annotated relation fields | A list of fields of the model on the other side of the relation | ["id"], ["firstName, lastName"] |
map | String | No | Defines a custom name for the foreign key in the database. | ["id"], ["firstName, lastName"] |
onUpdate | Enum. See Types of referential actions for values. | No | Defines the referential action to perform when a referenced entry in the referenced model is being updated. | Cascade, NoAction |
onDelete | Enum. See Types of referential actions for values. | No | Defines the referential action to perform when a referenced entry in the referenced model is being deleted. | Cascade, NoAction |
The name of the name argument on the @relation attribute can be omitted (references is required):
@relation(name: "UserOnPost", references: [id])
@relation("UserOnPost", references: [id])
// or
@relation(name: "UserOnPost")
@relation("UserOnPost")
@relation(_ name: String?, fields: FieldReference[]?, references: FieldReference[]?, onDelete: ReferentialAction?, onUpdate: ReferentialAction?, map: String?)
With SQLite, the signature changes to:
@relation(_ name: String?, fields: FieldReference[]?, references: FieldReference[]?, onDelete: ReferentialAction?, onUpdate: ReferentialAction?)
Note: Until version 3.0.0, the signature was:
prisma@relation(_ name: String?, fields: FieldReference[]?, references: FieldReference[]?)
See: The @relation attribute.
@mapMaps 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.
See Using custom model and field names to see how
@mapand@@mapchanges the generated Prisma Client.
@map does not rename the columns / fields in the database@map does change the field names in the generated clientYour @id field must include @map("_id"). For example:
model User {
id String @default(auto()) @map("_id") @db.ObjectId
}
| Name | Type | Required | Description | Example |
|---|---|---|---|---|
name | String | Yes | The database column (relational databases) or document field (MongoDB) name. | "comments", "someFieldName" |
The name of the name argument on the @map attribute can be omitted:
@map(name: "is_admin")
@map("users")
@map(_ name: String)
firstName field to a column called first_namemodel User {
id Int @id @default(autoincrement())
firstName String @map("first_name")
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
firstName String @map("first_name")
}
The generated client:
await prisma.user.create({
data: {
firstName: "Yewande", // first_name */} firstName
},
});
ADMIN to a database enum named adminenum Role {
ADMIN @map("admin")
CUSTOMER
}
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".
:::warning
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.
:::
@@mapMaps 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.
See Using custom model and field names to see how
@mapand@@mapchanges the generated Prisma Client.
| Name | Type | Required | Description | Example |
|---|---|---|---|---|
name | String | Yes | The database table (relational databases) or collection (MongoDB) name. | "comments", "someTableOrCollectionName" |
The name of the name argument on the @@map attribute can be omitted
@@map(name: "users")
@@map("users")
@@map(_ name: String)
User model to a database table/collection named usersmodel User {
id Int @id @default(autoincrement())
name String
@@map("users")
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
@@map("users")
}
The generated client:
await prisma.user.create({
// users */} user
data: {
name: "Yewande",
},
});
Role enum to a native enum in the database named _Role its values to lowercase values in the databaseenum Role {
ADMIN @map("admin")
CUSTOMER @map("customer")
@@map("_Role")
}
@updatedAtAutomatically 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.
DateTime fields:::warning
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.
:::
:::note
If you pass an empty update clause, the @updatedAt value will remain unchanged. For example:
await prisma.user.update({
where: {
id: 1,
},
data: {}, //<- Empty update clause
});
:::
N/A
@updatedAt
model Post {
id String @id
updatedAt DateTime @updatedAt
}
model Post {
id String @id @map("_id") @db.ObjectId
updatedAt DateTime @updatedAt
}
@ignoreAdd @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).
@ignore to fields that refer to invalid models when you introspect.The following example demonstrates manually adding @ignore to exclude the email field from Prisma Client:
model User {
id Int @id
name String
email String @ignore // this field will be excluded // [!code highlight]
}
@@ignoreAdd @@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.
@@ignore to an invalid model. (It also adds @ignore to relations pointing to such a model)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:
/// 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 // [!code highlight]
}
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:
/// 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 // [!code highlight]
}
model User {
id Int @id @default(autoincrement())
name String?
posts Post[] @ignore // [!code highlight]
}
@@schemaAdd @@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.
:::note
Multiple database schema support is only available with the PostgreSQL, CockroachDB, and SQL Server connectors.
:::
| Name | Type | Required | Description | Example |
|---|---|---|---|---|
name | String | Yes | The name of the database schema. | "base", "auth" |
The name of the name argument on the @@schema attribute can be omitted
@@schema(name: "auth")
@@schema("auth")
@@schema(_ name: String)
User model to a database schema named authgenerator client {
provider = "prisma-client"
output = "./generated"
}
datasource db {
provider = "postgresql"
schemas = ["auth"] // [!code highlight]
}
model User {
id Int @id @default(autoincrement())
name String
@@schema("auth") // [!code highlight]
}
:::info
For more information about using the multiSchema feature, refer to this guide.
:::
@shardKey:::note
This features requires the shardKeys Preview feature flag on your generator:
generator client {
provider = "prisma-client"
output = "../generated/prisma"
previewFeatures = ["shardKeys"]
}
:::
The @shardKey attribute is only compatible with PlanetScale databases. It enables you define a shard key on a field of your model:
model User {
id String @default(uuid())
region String @shardKey
}
@@shardKey:::note
This features requires the shardKeys Preview feature flag on your generator:
generator client {
provider = "prisma-client"
output = "../generated/prisma"
previewFeatures = ["shardKeys"]
}
:::
The @shardKey attribute is only compatible with PlanetScale databases. It enables you define a shard key on multiple fields of your model:
model User {
id String @default(uuid())
country String
customerId String
@@shardKey([country, customerId])
}
auto():::warning This function is available on MongoDB only. :::
Represents default values that are automatically generated by the database.
Used to generate an ObjectId for @id fields:
id String @map("_id") @db.ObjectId @default(auto())
The auto() function is not available on relational databases.
ObjectId (MongoDB only)model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String?
}
autoincrement():::warning
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:
| Database | Implementation |
|---|---|
| PostgreSQL | SERIAL type |
| MySQL | AUTO_INCREMENT attribute |
| SQLite | AUTOINCREMENT keyword |
| CockroachDB | SERIAL type |
model User {
id Int @id @default(autoincrement())
name String
}
sequence():::info
Only supported by CockroachDB
The sequence function is only supported by CockroachDB connector.
:::
Create a sequence of integers in the underlying database and assign the incremented values to the values of the created records based on the sequence.
| Argument | Example |
|---|---|
virtual | @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. |
model User {
id Int @id @default(sequence(maxValue: 4294967295))
name String
}
cuid()Generate a globally unique identifier based on the cuid spec.
If you'd like to use cuid2 values, you can pass 2 as an argument to the cuid function: cuid(2).
String.cuid() when using introspection by manually changing your Prisma schema and generating Prisma Client, in that case the values will be generated by Prisma's query engine.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.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.cuid() values as IDsmodel User {
id String @id @default(cuid())
name String
}
model User {
id String @id @default(cuid()) @map("_id")
name String
}
cuid(2) values as IDs based on the cuid2 specmodel User {
id String @id @default(cuid(2))
name String
}
model User {
id String @id @default(cuid(2)) @map("_id")
name String
}
uuid()Generate a globally unique identifier based on the UUID spec. Prisma ORM supports versions 4 (default) and 7.
String.uuid() when using introspection by manually changing your Prisma schema and generating Prisma Client, in that case the values will be generated by Prisma ORM's query engine.uuid() function, you can use the native database function with dbgenerated.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.uuid() values as IDs using UUID v4model User {
id String @id @default(uuid())
name String
}
model User {
id String @id @default(uuid()) @map("_id")
name String
}
uuid(7) values as IDs using UUID v7model User {
id String @id @default(uuid(7))
name String
}
model User {
id String @id @default(uuid(7)) @map("_id")
name String
}
ulid()Generate a universally unique lexicographically sortable identifier based on the ULID spec.
ulid() will produce 128-bit random identifier represented as a 26-character long alphanumeric string, e.g.: 01ARZ3NDEKTSV4RRFFQ69G5FAVulid() values as IDsmodel User {
id String @id @default(ulid())
name String
}
model User {
id String @id @default(ulid()) @map("_id")
name String
}
nanoid()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.
:::info
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:
:::
String.uuid() when using introspection by manually changing your Prisma schema and generating Prisma Client, in that case the values will be generated by Prisma ORM's query engine.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.nanoid() values with 21 characters as IDsmodel User {
id String @id @default(nanoid())
name String
}
model User {
id String @id @default(nanoid()) @map("_id")
name String
}
nanoid() values with 16 characters as IDsmodel User {
id String @id @default(nanoid(16))
name String
}
model User {
id String @id @default(nanoid(16)) @map("_id")
name String
}
now()Set a timestamp of the time when a record is created.
DateTime:::warning
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:
| Database | Implementation |
|---|---|
| PostgreSQL | CURRENT_TIMESTAMP and aliases like now() |
| MySQL | CURRENT_TIMESTAMP and aliases like now() |
| SQLite | CURRENT_TIMESTAMP and aliases like date('now') |
| CockroachDB | CURRENT_TIMESTAMP and aliases like now() |
model User {
id String @id
createdAt DateTime @default(now())
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
createdAt DateTime @default(now())
}
dbgenerated(...)Represents default values that cannot be expressed in the Prisma schema (such as random()).
Compatible with any scalar type
Can not be an empty string dbgenerated("") in 2.21.0 and later
Accepts a String value in 2.17.0 and later, which allows you to:
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)
Unsupported typecircle Unsupported("circle")? @default(dbgenerated("'<(10,4),11>'::circle"))
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 // [!code ++]
id String @id @default(uuid()) @db.Uuid // [!code --]
test String?
}
:::info
gen_random_uuid() is a PostgreSQL function. To use it in PostgreSQL versions 12.13 and earlier, you must enable the pgcrypto extension.
In Prisma ORM versions 4.5.0 and later, you can declare the pgcrypto extension in your Prisma schema with the postgresqlExtensions preview feature.
:::
FieldReference[]An array of field names: [id], [firstName, lastName]
StringA variable length text in double quotes: "", "Hello World", "Alice"
ExpressionAn expression that can be evaluated by Prisma ORM: 42.0, "", Bob, now(), cuid()
enum:::warning
Not supported Microsoft SQL Server
The Microsoft SQL Server connector does not support the enum type.
:::
Defines an enum .
Role instead of role, roles or Roles).[A-Za-z][A-Za-z0-9_]*enum with two possible valuesenum Role {
USER
ADMIN
}
model User {
id Int @id @default(autoincrement())
role Role
}
enum Role {
USER
ADMIN
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
role Role
}
enum with two possible values and set a default valueenum Role {
USER
ADMIN
}
model User {
id Int @id @default(autoincrement())
role Role @default(USER)
}
enum Role {
USER
ADMIN
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
role Role @default(USER)
}
type:::warning
Composite types are available for MongoDB only.
:::
:::info
Composite types are available in versions 3.12.0 and later, and in versions 3.10.0 and later if you enable the mongodb Preview feature flag.
:::
Defines a composite type .
Type names must:
[A-Za-z][A-Za-z0-9_]*Product model with a list of Photo composite typesmodel Product {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
photos Photo[]
}
type Photo {
height Int
width Int
url String
}