Skip to main content

PostgreSQL 扩展

本页面介绍 PostgreSQL 扩展,并讲解如何将其与 Prisma ORM 结合使用。

¥This page is about PostgreSQL extensions and explains how to use them with Prisma ORM.

警告

在 Prisma ORM v4.5.0 和 v6.16.0 之间,你可以通过 postgresqlExtensions 预览功能标志在 Prisma 模式中启用扩展。此功能标志在 v6.16.0 中已弃用,现在使用 PostgreSQL 扩展的推荐方法是通过 自定义迁移 安装它们。

¥Between Prisma ORM v4.5.0 and v6.16.0, you could enable extensions in the Prisma schema via the postgresqlExtensions preview feature flag. This feature flag has been deprecated in v6.16.0 and the recommended approach for using PostgreSQL extensions now is to install them via customized migrations.

什么是 PostgreSQL 扩展?

¥What are PostgreSQL extensions?

PostgreSQL 允许你通过安装和激活称为扩展的包来扩展数据库功能。例如,citext 扩展添加了不区分大小写的字符串数据类型。一些扩展,例如 citext,是由 PostgreSQL 直接提供的,而其他扩展是外部开发的。有关扩展的更多信息,请参阅 PostgreSQL 文档

¥PostgreSQL allows you to extend your database functionality by installing and activating packages known as extensions. For example, the citext extension adds a case-insensitive string data type. Some extensions, such as citext, are supplied directly by PostgreSQL, while other extensions are developed externally. For more information on extensions, see the PostgreSQL documentation.

要使用扩展,必须首先将其安装在数据库服务器的本地文件系统上。然后,你需要激活该扩展,该扩展运行一个添加新功能的脚本文件。

¥To use an extension, it must first be installed on the local file system of your database server. You then need to activate the extension, which runs a script file that adds the new functionality.

将 PostgreSQL 扩展与 Prisma ORM 结合使用

¥Using a PostgreSQL extension with Prisma ORM

让我们来看一个安装 citext 扩展的示例。

¥Let's walk through an example of installing the citext extension.

1. 创建一个空的迁移文件

¥ Create an empty migration

运行以下命令,创建一个可以执行 customize 操作的空迁移:

¥Run the following command to create an empty migration that you can customize:

npx prisma migrate dev --create-only

2. 添加 SQL 语句以安装扩展程序

¥ Add a SQL statement to install the extension

migrations 目录中创建的新迁移文件中,添加以下语句:

¥In the new migration file that was created in the migrations directory, add the following statement:

CREATE EXTENSION IF NOT EXISTS citext;

3. 部署迁移

¥ Deploy the migration

运行以下命令,部署迁移并将其应用到数据库:

¥Run the following command to deploy the migration and apply to your database:

npx prisma migrate deploy

4. 使用扩展

¥ Use the extension

现在,你可以在 Prisma 客户端的查询中使用该扩展。如果扩展程序包含当前无法在 Prisma 架构中原生表示的特殊数据类型,你仍然可以使用 Unsupported 后备类型在模型上定义该类型的字段。

¥You can now use the extension in your queries with Prisma Client. If the extension has special data types that currently can't be natively represented in the Prisma schema, you can still define fields of that type on your models using the Unsupported fallback type.