Skip to main content

多模式

概述

¥Overview

PostgreSQL、CockroachDB 和 SQL Server 允许你将数据库表组织到命名组中。这些组称为模式,充当逻辑分组表的命名空间(例如,为了避免名称冲突或更清晰地划分域),并允许你在它们之间定义外键约束。为避免歧义,本页将这些命名空间称为数据库架构。

¥PostgreSQL, CockroachDB, and SQL Server allow you to organize database tables into named groups. These groups are known as schemas and act as a namespace for logically grouping tables (e.g. to avoid name collisions or to have clearer domain separation) and let you define foreign key constraints across them. To avoid ambiguity, this page will refer to these namespaces as database schemas.

本页说明如何:

¥This page explains how to:

  • 在 Prisma 模式中包含多个数据库模式

    ¥include multiple database schemas in your Prisma schema

  • 使用 Prisma Migrate 将架构更改应用到数据库

    ¥apply your schema changes to your database with Prisma Migrate

  • 使用多个数据库模式内省现有数据库

    ¥introspect an existing database with multiple database schemas

  • 使用 Prisma Client 跨多个数据库模式进行查询

    ¥query across multiple database schemas with Prisma Client

注意

多模式功能仅支持 PostgreSQL、CockroachDB 和 SQL Server。它不适用于 SQLite 和 MySQL,因为这些数据库的架构概念与命名空间不同。

¥Multi-schema feature is only supported for PostgreSQL, CockroachDB, and SQL Server. It is not available for SQLite and MySQL because these databases don't have the same concept of schemas as namespaces.

如何在 Prisma 架构中包含多个数据库架构

¥How to include multiple database schemas in your Prisma schema

要在 Prisma 架构文件中使用多个数据库架构,请将数据库架构的名称添加到 datasource 块中 schemas 字段的数组中。以下示例添加 "base""shop" 架构:

¥To use multiple database schemas in your Prisma schema file, add the names of your database schemas to an array in the schemas field, in the datasource block. The following example adds a "base" and a "shop" schema:

schema.prisma
generator client {
provider = "prisma-client"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
schemas = ["base", "shop"]
}

你不需要更改连接字符串。连接字符串的 schema 值是 Prisma 客户端连接到并用于原始查询的默认数据库架构。所有其他 Prisma 客户端查询都使用你正在查询的模型或枚举的架构。

¥You do not need to change your connection string. The schema value of your connection string is the default database schema that Prisma Client connects to and uses for raw queries. All other Prisma Client queries use the schema of the model or enum that you are querying.

要指定模型或枚举属于特定数据库模式,请添加 @@schema 属性并将数据库模式名称作为参数。在以下示例中,User 模型是 "base" 架构的一部分,Order 模型和 Size 枚举是 "shop" 架构的一部分:

¥To designate that a model or enum belongs to a specific database schema, add the @@schema attribute with the name of the database schema as a parameter. In the following example, the User model is part of the "base" schema, and the Order model and Size enum are part of the "shop" schema:

schema.prisma
model User {
id Int @id
orders Order[]

@@schema("base")
}

model Order {
id Int @id
user User @relation(fields: [userId], references: [id])
userId Int

@@schema("shop")
}

enum Size {
Small
Medium
Large

@@schema("shop")
}

不同数据库模式中具有相同名称的表

¥Tables with the same name in different database schemas

如果不同数据库模式中具有相同名称的表,则需要将表名称映射到 Prisma 模式中的唯一模型名称。这可以避免你在 Prisma 客户端中查询模型时发生名称冲突。

¥If you have tables with the same name in different database schemas, you will need to map the table names to unique model names in your Prisma schema. This avoids name conflicts when you query models in Prisma Client.

例如,考虑 base 数据库模式中的 Config 表与 users 数据库模式中的 Config 表同名的情况。为了避免名称冲突,请为 Prisma 架构中的模型指定唯一名称(BaseConfigUserConfig),并使用 @@map 属性将每个模型映射到相应的表名称:

¥For example, consider a situation where the Config table in the base database schema has the same name as the Config table in the users database schema. To avoid name conflicts, give the models in your Prisma schema unique names (BaseConfig and UserConfig) and use the @@map attribute to map each model to the corresponding table name:

schema.prisma
model BaseConfig {
id Int @id

@@map("Config")
@@schema("base")
}

model UserConfig {
id Int @id

@@map("Config")
@@schema("users")
}

如何使用 Prisma Migrate 应用架构更改

¥How to apply your schema changes with Prisma Migrate

你可以使用 Prisma Migrate(或 prisma db push)将更改应用于具有多个数据库模式的 Prisma 模式。

¥You can use Prisma Migrate (or prisma db push) to apply changes to a Prisma schema with multiple database schemas.

例如,将 Profile 模型添加到上面的 base 架构中:

¥As an example, add a Profile model to the base schema above:

schema.prisma
model User {
id Int @id
orders Order[]
profile Profile?

@@schema("base")
}

model Profile {
id Int @id @default(autoincrement())
bio String
user User @relation(fields: [userId], references: [id])
userId Int @unique

@@schema("base")
}

model Order {
id Int @id
user User @relation(fields: [userId], references: [id])
userId Int

@@schema("shop")
}

enum Size {
Small
Medium
Large

@@schema("shop")
}

然后,你可以将此架构更改应用到你的数据库。例如,你可以使用 migrate dev 创建架构更改并将其应用为迁移:

¥You can then apply this schema change to your database. For example, you can use migrate dev to create and apply your schema changes as a migration:

npx prisma migrate dev --name add_profile

请注意,如果你将模型或枚举从一个模式移动到另一个模式,Prisma ORM 将从源模式中删除该模型或枚举,并在目标模式中创建一个新模型或枚举。

¥Note that if you move a model or enum from one schema to another, Prisma ORM deletes the model or enum from the source schema and creates a new one in the target schema.

如何使用多个数据库模式内省现有数据库

¥How to introspect an existing database with multiple database schemas

你可以使用 prisma db pull 内省具有多个数据库模式的现有数据库,就像内省具有单个数据库模式的数据库一样:

¥You can introspect an existing database that has multiple database schemas in the same way that you introspect a database that has a single database schema, using prisma db pull:

npx prisma db pull

这会更新你的 Prisma 架构以匹配数据库的当前状态。

¥This updates your Prisma schema to match the current state of the database.

如果不同数据库模式中有同名的表,Prisma ORM 会显示一条验证错误,指出存在冲突。为了解决这个问题,使用 @map 属性重命名内省模型.

¥If you have tables with the same name in different database schemas, Prisma ORM shows a validation error pointing out the conflict. To fix this, rename the introspected models with the @map attribute.

如何使用 Prisma Client 跨多个数据库模式进行查询

¥How to query across multiple database schemas with Prisma Client

你可以在多个数据库模式中查询模型,而无需对 Prisma 客户端查询语法进行任何更改。例如,以下查询使用上面的 Prisma 架构查找给定用户的所有订单:

¥You can query models in multiple database schemas without any change to your Prisma Client query syntax. For example, the following query finds all orders for a given user, using the Prisma schema above:

const orders = await prisma.order.findMany({
where: {
user: {
id: 42,
},
},
})

外部管理表

¥Externally managed tables

有时,你可能不希望 Prisma ORM 管理特定的表,例如由其他团队或服务处理的表(例如,Auth0 或 Clerk 表)。在这种情况下,你可以使用 Prisma 配置文件 中的 tables.external 配置选项将这些表标记为外部管理表。了解有关 外部管理表 的更多信息。

¥Sometimes, you might not want Prisma ORM to manage specific tables, such as ones handled by another team or service (e.g., Auth0 or Clerk tables). In such cases, you can mark these as externally managed tables using the tables.external configuration option in your Prisma Config file. Learn more about externally managed tables.