![]() |
想旅行的凉面 · 格尔木藏格锂业有限公司-柴达木循环经济试验区 ...· 6 月前 · |
![]() |
闯红灯的爆米花 · 哈尔滨经济技术开发区管理委员会—自贸要闻—哈 ...· 6 月前 · |
![]() |
正直的香瓜 · 如何选择微型直流电动机的类型· 7 月前 · |
![]() |
淡定的排球 · 《民法典》宣传:高空抛物不可取· 8 月前 · |
![]() |
满身肌肉的梨子 · 麒麟软件、统信UOS、麒麟信安,哪家国产操作 ...· 10 月前 · |
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) | Connection URL including authentication info. Most connectors use the syntax provided by the database . |
shadowDatabaseUrl
|
No | String (URL) | Connection URL to the shadow database used by Prisma Migrate. Allows you to use a cloud-hosted database as the shadow database. |
directUrl
|
No | String (URL) |
Connection URL for
direct connection to the database
.
If you use a connection pooler URL in the
url
argument (for example, if you use the Data Proxy or pgBouncer), Prisma CLI commands
that require a direct connection to the database
use the URL in the
directUrl
argument.
The
directUrl
property is supported by Prisma Studio from version 5.1.0 upwards.
|
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 versions 4.5.0 and later. |
The following providers are available:
In this example, the target database is available with the following credentials:
johndoe
mypassword
localhost
5432
mydb
public
datasource 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:
johndoe
mypassword
localhost
5432
mydb
public
datasource db {provider = "postgresql"url = env("DATABASE_URL")}
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
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:
johndoe
mypassword
localhost
3306
mydb
datasource db {provider = "mysql"url = "mysql://johndoe:mypassword@localhost:3306/mydb"}
Learn more about MySQL connection strings here .
root
password
cluster1.test1.mongodb.net
testing
datasource 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 available with the following credentials:
johndoe
mypassword
localhost
26257
mydb
public
datasource 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 .
A
generator
block accepts the following fields:
Name | Required | Type | Description | |
---|---|---|---|---|
provider
|
Yes |
String (file path) or Enum (
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
|
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 |
prisma-client-js
generator with the default
output
,
previewFeatures
,
engineType
and
binaryTargets
generator 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"]}
[A-Za-z][A-Za-z0-9_]*
User
instead of
user
,
users
or
Users
)
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
).
[A-Za-z][A-Za-z0-9_]*
Note : You can use the
@map
attribute 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")
.
The data source connector determines what native database type each of Prisma 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.
Native database type | Native database type attribute | Notes |
---|---|---|
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)}
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.
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
|
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())
|
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.
Not supported by MongoDB
The
MongoDB connector
does not support the
Unsupported
type.
The
Unsupported
type was introduced in
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 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"
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.
Corresponding database type:
Every model must define an
@id
field
The
, 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 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()
value that uses
the
auto()
function
to auto-generate an
ObjectId
id String @db.ObjectId @map("_id") @default(auto())
cuid()
and
uuid()
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. |
In the following example,
id
does not have a default value:
model User {id String @idname 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 @idauthor User @relation(fields: [authorId], references: [id])bio String}model User {id Int @idemail String @uniquename 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,},},},})
PRIMARY KEY
@default()
value that uses
functions
to auto-generate an ID
String
,
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])
String
fields
model User {firstName StringlastName Stringemail String @uniqueisAdmin 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
model User {firstName StringlastName Stringemail String @uniqueisAdmin 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 Stringpublished Boolean @default(false)author User @relation(fields: [authorId], references: [id])authorId Int@@id([authorId, title])}model User {id Int @default(autoincrement())email String @uniquename 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]',},},},})
Corresponding database type:
DEFAULT
Default values can be a static value (
4
,
"hello"
) or one of the following
functions
:
autoincrement()
sequence()
(CockroachDB only)
dbgenerated()
cuid()
uuid()
now()
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 can be a static value (
4
,
"hello"
) or one of the following
functions
:
Default values are currently not allowed on relation fields in the Prisma schema.
Default values can be used with scalar lists in databases that natively support them.
model User {id Int @id @default( autoincrement())posts Post[]favoriteColors String[] @default(["red", "yellow", "purple"])roles Role[] @default([USER, DEVELOPER])}enum Role {USERDEVELOPERADMIN}
@unique
can be optional or required
@unique
must
be required if it represents the only unique constraint on a model without an
@id
/
@@id
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. |
authorId
model Post {author User @relation(fields: [authorId], references: [id])authorId Int @uniquetitle Stringpublished Boolean @default(false)}model User {id Int @id @default(autoincrement())email String? @uniquename StringPost 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 Intlastname Intid 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 | nullJohn | Smith | null
A model can have any number of
@@unique
blocks
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)])
@@unique(_ fields: FieldReference[], name: String?, map: String?)
Note : Before version 4.0.0, or before version 3.5.0 with the
extendedIndexes
Preview feature enabled, the signature was:
@@unique(_ fields: FieldReference[], name: String?, map: String?)
Note : Before version 3.0.0, the signature was:
@@unique(_ fields: FieldReference[], name: String?)
String
fields
model User {id Int @default(autoincrement())firstName StringlastName StringisAdmin 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
field
model User {id Int @default(autoincrement())firstName StringlastName StringisAdmin Boolean @default(false)@@unique([firstName, lastName, isAdmin])}
model Post {id Int @default(autoincrement())author User @relation(fields: [authorId], references: [id])authorId Inttitle Stringpublished Boolean @default(false)@@unique([authorId, title])}model User {id Int @id @default(autoincrement())email String @uniqueposts Post[]}
name
for a multi-field unique attribute
model User {id Int @default(autoincrement())firstName StringlastName StringisAdmin 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,},},})
INDEX
CREATE INDEX title ON public."Post"((lower(title)) text_ops);
)
WHERE
CONCURRENTLY
While you cannot configure these option in your Prisma schema, you can still configure them on the database-level directly.
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)])
model Post {id Int @id @default(autoincrement())title Stringcontent String?@@index([title])}
model Post {id Int @id @default(autoincrement())title Stringcontent String?@@index([title, content])}
model Post {id Int @id @default(autoincrement())title Stringcontent String?@@index(fields: [title, content], name: "main_index")}
type Address {street Stringnumber Int}model User {id Int @idemail Stringaddress Address@@index([address.number])}
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:
@relation(_ name: String?, fields: FieldReference[]?, references: FieldReference[]?)
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.
See Using custom model and field names to see how
@map
and@@map
changes the generated Prisma Client.
firstName
field to a column called
first_name
model User {id Int @id @default(autoincrement())firstName String @map("first_name")}
The generated client:
await prisma.user.create({data: {firstName: 'Yewande', // first_name --> firstName},})
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.
See Using custom model and field names to see how
@map
and@@map
changes the generated Prisma Client.
User
model to a database table/collection named
users
model User {id Int @id @default(autoincrement())name String@@map("users")}
The generated client:
await prisma.user.create({// users --> userdata: {name: 'Yewande',},})
Role
enum to a native enum in the database named
_Role
its values to lowercase values in the database
enum Role {ADMIN @map("admin")CUSTOMER @map("customer")@@map("_Role")}
Add
@ignore
to a field that you want to exclude from Prisma Client (for example, a field that you do not want Prisma 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).
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
1/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.2model Post {3 id Int @default(autoincrement()) // no unique identifier4 author User @relation(fields: [authorId], references: [id])5 authorId Int67 @@ignore8}
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
1/// The underlying table does not contain a valid unique identifier and can therefore currently not be handled by Prisma Client.2model Post {3 id Int @default(autoincrement()) // no unique identifier4 author User @relation(fields: [authorId], references: [id])5 authorId Int67 @@ignore8}910model User {11 id Int @id @default(autoincrement() )12 name String?13 posts Post[] @ignore14}
To use this attribute, you must have the preview feature enabled. Multiple database schema support is currently available with the PostgreSQL, CockroachDB, and SQL Server connectors.
Add
@@schema
to a model to specify which schema in your database should contain the table associated with that model.
User
model to a database schema named
auth
generator client {provider = "prisma-client-js"previewFeatures = ["multiSchema"]}datasource db {provider = "postgresql"url = env("DATABASE_URL")schemas = ["auth"]}model User {id Int @id @default(autoincrement())name String@@schema("auth")}
For more information about using the
multiSchema
feature, refer to
this guide
.
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 | type |
MySQL | attribute |
SQLite | keyword |
CockroachDB | type |
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
.
|
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 errors such as
Error: The provided value for the column is too long for the column's type.
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's
query engine
.
Note (Relational databases)
: If you do not want to use Prisma's
uuid()
function, you can use
the native database function with
dbgenerated
.
Implemented on the database-level, meaning that it manifests in the database schema and can be recognized through introspection. Database implementations:
Database | Implementation |
---|---|
PostgreSQL |
and aliases like
now()
|
MySQL |
and aliases like
now()
|
SQLite |
CURRENT_TIMESTAMP
and aliases like
date('now')
|
CockroachDB |
and aliases like
now()
|
Compatible with any type
If a value is present, it cannot be empty (for example,
dbgenerated("")
) -
and later
Accepts a
String
value in
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. (
)
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's
uuid()
:
model User {id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuidid String @id @default(uuid()) @db.Uuidtest String?}
Note
:
. To use it in PostgreSQL versions 12.13 and earlier, you must enable the
pgcrypto
extension.
In Prisma versions 4.5.0 and later, you can declare the
pgcrypto
extension in your Prisma schema with the
postgresqlExtensions
preview feature
.
enum
with two possible values
enum Role {USERADMIN}model User {id Int @id @default(autoincrement())role Role}
enum
with two possible values and set a default value
enum Role {USERADMIN}model User {id Int @id @default(autoincrement())role Role @default(USER)}