Prisma Schema 概述
Prisma Schema(或简称为 schema)是 Prisma ORM 设置的主要配置方法。它由以下部分组成:
¥The Prisma Schema (or schema for short) is the main method of configuration for your Prisma ORM setup. It consists of the following parts:
-
数据源:指定 Prisma ORM 应连接的数据源的详细信息(例如 PostgreSQL 数据库)
¥Data sources: Specify the details of the data sources Prisma ORM should connect to (e.g. a PostgreSQL database)
-
生成器:指定应根据数据模型生成哪些客户端(例如 Prisma 客户端)
¥Generators: Specifies what clients should be generated based on the data model (e.g. Prisma Client)
-
数据模型定义:指定你的应用 models(每个数据源的数据形状)及其 relations
¥Data model definition: Specifies your application models (the shape of the data per data source) and their relations
它通常是一个名为 schema.prisma
的单个文件(或具有 .prisma
文件扩展名的多个文件),存储在已定义但可自定义的 location 中。如果你愿意,也可以 将 Prisma Schema 组织到多个文件中。
¥It is typically a single file called schema.prisma
(or multiple files with .prisma
file extension) that is stored in a defined but customizable location. You can also organize your Prisma schema in multiple files if you prefer that.
¥See the Prisma schema API reference
有关架构每个部分的详细信息。
¥for detailed information about each section of the schema.
每当调用 prisma
命令时,CLI 通常会从模式中读取一些信息,例如:
¥Whenever a prisma
command is invoked, the CLI typically reads some information from the schema, e.g.:
-
prisma generate
:从 Prisma 架构中读取上述所有信息,以生成正确的数据源客户端代码(例如 Prisma 客户端)。¥
prisma generate
: Reads all above mentioned information from the Prisma schema to generate the correct data source client code (e.g. Prisma Client). -
prisma migrate dev
:读取数据源和数据模型定义以创建新的迁移。¥
prisma migrate dev
: Reads the data sources and data model definition to create a new migration.
你还可以在架构内部使用 使用环境变量 来在调用 CLI 命令时提供配置选项。
¥You can also use environment variables inside the schema to provide configuration options when a CLI command is invoked.
示例
¥Example
以下是 Prisma Schema 的示例,它指定:
¥The following is an example of a Prisma Schema that specifies:
-
数据源(PostgreSQL 或 MongoDB)
¥A data source (PostgreSQL or MongoDB)
-
生成器(Prisma 客户端)
¥A generator (Prisma Client)
-
具有两个模型(具有一个关系)和一个
enum
的数据模型定义¥A data model definition with two models (with one relation) and one
enum
-
若干 原生数据类型属性 (
@db.VarChar(255)
,@db.ObjectId
)¥Several native data type attributes (
@db.VarChar(255)
,@db.ObjectId
)
- Relational databases
- MongoDB
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
email String @unique
name String?
role Role @default(USER)
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
published Boolean @default(false)
title String @db.VarChar(255)
author User? @relation(fields: [authorId], references: [id])
authorId Int?
}
enum Role {
USER
ADMIN
}
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
createdAt DateTime @default(now())
email String @unique
name String?
role Role @default(USER)
posts Post[]
}
model Post {
id String @id @default(auto()) @map("_id") @db.ObjectId
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
published Boolean @default(false)
title String
author User? @relation(fields: [authorId], references: [id])
authorId String @db.ObjectId
}
enum Role {
USER
ADMIN
}
语法
¥Syntax
Prisma Schema 文件以 Prisma Schema 语言 (PSL) 编写。查看 数据源、generators、数据模型定义 以及 Prisma Schema API 参考 页面以了解详细信息和示例。
¥Prisma Schema files are written in Prisma Schema Language (PSL). See the data sources, generators, data model definition and of course Prisma Schema API reference pages for details and examples.
VS Code
PSL 的语法高亮可通过 VS Code 扩展 实现(它还允许你自动格式化 Prisma 架构的内容并用红色波浪线指示语法错误)。了解有关 在编辑器中设置 Prisma ORM 的更多信息。
¥Syntax highlighting for PSL is available via a VS Code extension (which also lets you auto-format the contents of your Prisma schema and indicates syntax errors with red squiggly lines). Learn more about setting up Prisma ORM in your editor.
GitHub
GitHub 上的 PSL 代码片段也可以通过语法高亮来渲染,方法是使用 .prisma
文件扩展名或使用 prisma
在 Markdown 中注释受隔离的代码块:
¥PSL code snippets on GitHub can be rendered with syntax highlighting as well by using the .prisma
file extension or annotating fenced code blocks in Markdown with prisma
:
```prisma
model User {
id Int @id @default(autoincrement())
createdAt DateTime @default(now())
email String @unique
name String?
}
```
从架构访问环境变量
¥Accessing environment variables from the schema
你可以在调用 CLI 命令或运行 Prisma Client 查询时使用环境变量来提供配置选项。
¥You can use environment variables to provide configuration options when a CLI command is invoked, or a Prisma Client query is run.
直接在架构中硬编码 URL 是可能的,但不鼓励这样做,因为它会带来安全风险。在架构中使用环境变量允许你将密钥保留在架构之外,从而通过允许你在不同环境中使用它来提高架构的可移植性。
¥Hardcoding URLs directly in your schema is possible but is discouraged because it poses a security risk. Using environment variables in the schema allows you to keep secrets out of the schema which in turn improves the portability of the schema by allowing you to use it in different environments.
可以使用 env()
函数访问环境变量:
¥Environment variables can be accessed using the env()
function:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
你可以在以下位置使用 env()
函数:
¥You can use the env()
function in the following places:
-
数据源网址
¥A datasource url
-
生成器二进制目标
¥Generator binary targets
有关如何在开发过程中使用 .env
文件的更多信息,请参阅 环境变量。
¥See Environment variables for more information about how to use an .env
file during development.
评论
¥Comments
Prisma Schema Language 支持两种类型的注释:
¥There are two types of comments that are supported in Prisma Schema Language:
-
// comment
:此注释是为了读者的清晰度,并不存在于模式的抽象语法树 (AST) 中。¥
// comment
: This comment is for the reader's clarity and is not present in the abstract syntax tree (AST) of the schema. -
/// comment
:这些注释将显示在模式的抽象语法树 (AST) 中,作为 AST 节点的描述。然后,工具可以使用这些注释来提供附加信息。所有评论都附加到下一个可用节点 - 自由浮动的评论 不受支持,也不包含在 AST 中。¥
/// comment
: These comments will show up in the abstract syntax tree (AST) of the schema as descriptions to AST nodes. Tools can then use these comments to provide additional information. All comments are attached to the next available node - free-floating comments are not supported and are not included in the AST.
以下是一些不同的示例:
¥Here are some different examples:
/// This comment will get attached to the `User` node in the AST
model User {
/// This comment will get attached to the `id` node in the AST
id Int @default(autoincrement())
// This comment is just for you
weight Float /// This comment gets attached to the `weight` node
}
// This comment is just for you. It will not
// show up in the AST.
/// This comment will get attached to the
/// Customer node.
model Customer {}
自动格式化
¥Auto formatting
Prisma ORM 支持自动格式化 .prisma
文件。格式化 .prisma
文件有两种方法:
¥Prisma ORM supports formatting .prisma
files automatically. There are two ways to format .prisma
files:
-
¥Run the
prisma format
命令。
¥command.
-
安装 Prisma VS Code 扩展 并调用 VS Code 格式操作 - 手动或保存时。
¥Install the Prisma VS Code extension and invoke the VS Code format action - manually or on save.
没有配置选项 - 格式规则 是固定的(类似于 Golang 的 gofmt
,但与 Javascript 的 prettier
不同):
¥There are no configuration options - formatting rules are fixed (similar to Golang's gofmt
but unlike Javascript's prettier
):
格式规则
¥Formatting rules
配置块按其 =
符号对齐
¥Configuration blocks are aligned by their =
sign
block _ {
key = "value"
key2 = 1
long_key = true
}
字段定义对齐到由 2 个或更多空格分隔的列中
¥Field definitions are aligned into columns separated by 2 or more spaces
block _ {
id String @id
first_name LongNumeric @default
}
空行将重置块对齐和格式规则
¥Empty lines resets block alignment and formatting rules
block _ {
key = "value"
key2 = 1
key10 = true
long_key = true
long_key_2 = true
}
block _ {
id String @id
@default
first_name LongNumeric @default
}
多行字段属性与其余字段属性正确对齐
¥Multiline field attributes are properly aligned with the rest of the field attributes
block _ {
id String @id
@default
first_name LongNumeric @default
}
块属性被排序到块的末尾
¥Block attributes are sorted to the end of the block
block _ {
key = "value"
@@attribute
}