相关文章推荐
坚韧的跑步鞋  ·  Horizontal scroll ...·  1 周前    · 
耍酷的自行车  ·  PyCharm+Qt ...·  9 月前    · 
失落的炒饭  ·  swing日期选择器 - 酷米网·  10 月前    · 
发财的煎饼果子  ·  safedelete.models — ...·  1 年前    · 
Fields

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:

Specify a PostgreSQL data source

In this example, the target database is available with the following credentials:

  • User: johndoe
  • Password: mypassword
  • Host: localhost
  • Port: 5432
  • Database name: mydb
  • Schema name: public
datasource db {
provider = "postgresql"
url = "postgresql://johndoe:mypassword@localhost:5432/mydb?schema=public"
}

Learn more about PostgreSQL connection strings here .

Specify a PostgreSQL data source via an environment variable

In this example, the target database is available with the following credentials:

  • User: johndoe
  • Password: mypassword
  • Host: localhost
  • Port: 5432
  • Database name: mydb
  • Schema name: public
datasource db {
provider = "postgresql"
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

Specify a MySQL data source

In this example, the target database is available with the following credentials:

  • User: johndoe
  • Password: mypassword
  • Host: localhost
  • Port: 3306
  • Database name: mydb
datasource db {
provider = "mysql"
url = "mysql://johndoe:mypassword@localhost:3306/mydb"
}

Learn more about MySQL connection strings here .

Specify a MongoDB data source

  • User: root
  • Password: password
  • Host: cluster1.test1.mongodb.net
  • Port: N/A
  • Database name: testing
datasource db {
provider = "mongodb"
url = "mongodb+srv://root:[email protected]/testing?retryWrites=true&w=majority"
}

Learn more about MongoDB connection strings here .

Specify a CockroachDB data source

In this example, the target database is available with the following credentials:

  • User: johndoe
  • Password: mypassword
  • Host: localhost
  • Port: 26257
  • Database name: mydb
  • Schema name: 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 .

Fields

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

Linux (Ubuntu), x86_64

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
Specify the 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"]
}

Naming conventions

  • Model names must adhere to the following regular expression: [A-Za-z][A-Za-z0-9_]*
  • Model names must start with a letter and are typically spelled in
  • Model names should use the singular form (for example, User instead of user , users or Users )
  • Prisma has a number of reserved words that are being used by Prisma internally and therefore cannot be used as a model name. You can find the reserved words and .

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 ).

Naming conventions

  • Must start with a letter
  • Typically spelled in camelCase
  • Must adhere to the following regular expression: [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") .

model field scalar types

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.

MySQL

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)
}

CockroachDB

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.

MySQL

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

CockroachDB

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())

CockroachDB

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.

Unsupported

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 .

Remarks

  • 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

Attributes modify the behavior of a field or block (e.g. models ). There are two ways to add attributes to your data model:

  • Field attributes are prefixed with @
  • Block attributes are prefixed with @@

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.

MongoDB

  • 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

Arguments

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.

Single-field IDs without default values

In the following example, id does not have a default value:

Relational databases
MongoDB
model User {
id String @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',
},
})
Specify an ID on relation scalar field without a default value

In the following example, authorId is a both a relation scalar and the ID of Profile :

Relational databases
MongoDB
model Profile {
authorId Int @id
author User @relation(fields: [authorId], references: [id])
bio String
}
model User {
id Int @id
email String @unique
name String?
profile Profile?
}

In this scenario, you cannot create a Profile only - you must use Prisma Client's nested writes create a 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,
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,
},
},
},
})

Remarks

  • Corresponding database type: PRIMARY KEY
  • Can be annotated with a @default() value that uses functions to auto-generate an ID
  • Cannot be optional
  • Can be defined on any scalar field ( String , Int , enum )
  • Cannot be defined on a relation field
  • The name of the composite ID field in Prisma Client has the following pattern: field1_field2_field3

Arguments

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])

Specify a multi-field ID on two 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 :

Relational databases only
const user = await prisma.user.create({
data: {
firstName: 'Alice',
lastName: 'Smith',
},
})

To retrieve a user, use the generated composite ID field ( firstName_lastName ):

Relational databases only
const user = await prisma.user.findUnique({
where: {
firstName_lastName: {
firstName: 'Alice',
lastName: 'Smith',
},
},
})
Specify a multi-field ID on two 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 :

Relational databases only
const user = await prisma.user.create({
data: {
firstName: 'Alice',
lastName: 'Smith',
isAdmin: true,
},
})
Specify a multi-field ID that includes a relation field
Relational databases only
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 :

Relational databases only
const post = await prisma.post.create({
data: {
title: 'Hello World',
author: {
connect: {
},
},
},
})

Relational databases

  • Corresponding database type: DEFAULT

  • Default values can be a static value ( 4 , "hello" ) or one of the following functions :

  • 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.

MongoDB
  • 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.

Default values for scalar lists

Relational databases
MongoDB
model User {
id Int @id @default(autoincrement())
posts Post[]
favoriteColors String[] @default(["red", "yellow", "purple"])
roles Role[] @default([USER, DEVELOPER])
}
enum Role {
USER
DEVELOPER
ADMIN
}

General

  • A field annotated with @unique can be optional or required
  • A field annotated with @unique must be required if it represents the only unique constraint on a model without an @id / @@id
  • A model can have any number of unique constraints
  • Can be defined on any scalar field
  • Cannot be defined on a relation field
Arguments
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.
  • ¹ Can be required by some of the index and field types.

Specify a unique attribute on relation scalar field authorId

Relational databases
MongoDB
model Post {
author User @relation(fields: [authorId], references: [id])
authorId Int @unique
title String
published Boolean @default(false)
}
model User {
id Int @id @default(autoincrement())
email String? @unique
name String
Post Post[]
}
General
  • 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

Arguments
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)])

Signature

@@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?)

Specify a multi-field unique attribute on two String fields

Relational databases
MongoDB
model User {
id Int @default(autoincrement())
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,
},
},
})
Specify a multi-field unique attribute on two String fields and one Boolean field
Relational databases
MongoDB
model User {
id Int @default(autoincrement())
firstName String
lastName String
isAdmin Boolean @default(false)
@@unique([firstName, lastName, isAdmin])
}
Specify a multi-field unique attribute that includes a relation field
Relational databases
MongoDB
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[]
}
Specify a custom name for a multi-field unique attribute
Relational databases
MongoDB
model User {
id Int @default(autoincrement())
firstName String
lastName String
isAdmin Boolean @default(false)
@@unique(fields: [firstName, lastName, isAdmin], name: "admin_identifier")
}

To retrieve a user, use the custom field name ( admin_identifier ):

const user = await prisma.user.findUnique({
where: {
admin_identifier: {
firstName: 'Alice',
lastName: 'Smith',
isAdmin: true,
},
},
})

Relational databases

  • Corresponding database type: INDEX
  • There are some additional index configuration options that cannot be provided via the Prisma schema yet. These include:
    • PostgreSQL and CockroachDB:
      • Define index fields as expressions (e.g. CREATE INDEX title ON public."Post"((lower(title)) text_ops); )
      • Define partial indexes with WHERE
      • Create indexes concurrently with CONCURRENTLY

While you cannot configure these option in your Prisma schema, you can still configure them on the database-level directly.

Arguments
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)])

Define a single-column index

Relational databases only
model Post {
id Int @id @default(autoincrement())
title String
content String?
@@index([title])
}
Define a multi-column index
Relational databases only
model Post {
id Int @id @default(autoincrement())
title String
content String?
@@index([title, content])
}
Define an index with a name
Relational databases only
model Post {
id Int @id @default(autoincrement())
title String
content String?
@@index(fields: [title, content], name: "main_index")
}
Define an index on a composite type field
MongoDB
type Address {
street String
number Int
}
model User {
id Int @id
email String
address Address
@@index([address.number])
}

Arguments

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")

Signature

@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[]?)

@map

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.

Map the firstName field to a column called first_name

Relational databases
MongoDB
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
},
})
@@map

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.

Map the User model to a database table/collection named users

Relational databases
MongoDB
model User {
id Int @id @default(autoincrement())
name String
@@map("users")
}

The generated client:

await prisma.user.create({
// users --> user
data: {
name: 'Yewande',
},
})
Map the 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")
}

@ignore

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).

Examples

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 identifier
4 author User @relation(fields: [authorId], references: [id])
5 authorId Int
6
7 @@ignore
8}

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 identifier
4 author User @relation(fields: [authorId], references: [id])
5 authorId Int
6
7 @@ignore
8}
9
10model User {
11 id Int @id @default(autoincrement())
12 name String?
13 posts Post[] @ignore
14}

@@schema

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.

Map the 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 .

Remarks

  • 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

Optional arguments

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 .

Remarks

  • Compatible with String
  • Implemented by Prisma and therefore not "visible" in the underlying database schema. You can still use 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 .
  • Since the length of cuid() output is undefined per the cuid creator, a safe field size is 30 characters, in order to allow for enough characters for very large values. If you set the field size as less than 30, and then a larger value is generated by cuid() , you might see Prisma errors such as Error: The provided value for the column is too long for the column's type.
Remarks

Note (Relational databases) : If you do not want to use Prisma's uuid() function, you can use the native database function with dbgenerated .

Relational databases
  • 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()
Relational databases
  • 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. ( )

Override default value behavior for supported types

Relational databases only

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.Uuid
id String @id @default(uuid()) @db.Uuid
test 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 .

Specify an enum with two possible values

Relational databases
MongoDB
enum Role {
USER
ADMIN
}
model User {
id Int @id @default(autoincrement())
role Role
}

Specify an enum with two possible values and set a default value

Relational databases
MongoDB
enum Role {
USER
ADMIN
}
model User {
id Int @id @default(autoincrement())
role Role @default(USER)
}