PostgreSQL
PostgreSQL 数据源连接器将 Prisma ORM 连接到 PostgreSQL 数据库服务器。
¥The PostgreSQL data source connector connects Prisma ORM to a PostgreSQL database server.
默认情况下,PostgreSQL 连接器包含负责连接到数据库的数据库驱动程序。你可以使用 驱动适配器(预览版)通过 Prisma 客户端中的 JavaScript 数据库驱动程序连接到数据库。
¥By default, the PostgreSQL connector contains a database driver responsible for connecting to your database. You can use a driver adapter (Preview) to connect to your database using a JavaScript database driver from Prisma Client.
昨天需要 Postgres 实例吗?
¥Need a Postgres instance yesterday?
使用 Prisma Postgres,你只需三次单击即可在裸机上运行数据库。连接池、查询缓存和自动备份都包括在内。 立即开始。
¥With Prisma Postgres you can get a database running on bare-metal in three clicks. Connection pooling, query caching, and automated backups are all included. to get started today.
想要更快的方式开始使用 Prisma Postgres?只需在你的终端中运行 npx prisma init --db
。🚀
¥Want any even faster way to get started with Prisma Postgres? Just run npx prisma init --db
in your terminal. 🚀
示例
¥Example
要连接到 PostgreSQL 数据库服务器,你需要在 Prisma 架构 中配置 datasource
块:
¥To connect to a PostgreSQL database server, you need to configure a datasource
block in your Prisma schema:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
传递到 datasource
块的字段是:
¥The fields passed to the datasource
block are:
-
provider
:指定postgresql
数据源连接器。¥
provider
: Specifies thepostgresql
data source connector. -
url
:为 PostgreSQL 数据库服务器指定 连接网址。在本例中,使用环境变量 提供连接 URL。¥
url
: Specifies the connection URL for the PostgreSQL database server. In this case, an environment variable is used to provide the connection URL.
使用 node-postgres
驱动程序
¥Using the node-postgres
driver
从 v5.4.0
开始,你可以将 Prisma ORM 与 JavaScript 生态系统中的数据库驱动程序一起使用(而不是使用 Prisma ORM 的内置驱动程序)。你可以使用 驱动适配器 来完成此操作。
¥As of v5.4.0
, you can use Prisma ORM with database drivers from the JavaScript ecosystem (instead of using Prisma ORM's built-in drivers). You can do this by using a driver adapter.
对于 PostgreSQL,node-postgres
(pg
) 是 JavaScript 生态系统中最流行的驱动程序之一。它可以与任何通过 TCP 访问的 PostgreSQL 数据库一起使用。
¥For PostgreSQL, node-postgres
(pg
) is one of the most popular drivers in the JavaScript ecosystem. It can be used with any PostgreSQL database that's accessed via TCP.
本节介绍如何将其与 Prisma ORM 和 @prisma/adapter-pg
驱动程序适配器一起使用。
¥This section explains how you can use it with Prisma ORM and the @prisma/adapter-pg
driver adapter.
1. 启用 driverAdapters
预览功能标志
¥ Enable the driverAdapters
Preview feature flag
由于驱动程序适配器当前位于 预览 中,因此你需要在 Prisma 架构中的 datasource
块上启用其功能标志:
¥Since driver adapters are currently in Preview, you need to enable its feature flag on the datasource
block in your Prisma schema:
generator client {
provider = "prisma-client-js"
previewFeatures = ["driverAdapters"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
将功能标志添加到架构后,重新生成 Prisma 客户端:
¥Once you have added the feature flag to your schema, re-generate Prisma Client:
npx prisma generate
2. 安装依赖
¥ Install the dependencies
接下来,安装 Prisma ORM 的 pg
驱动程序适配器:
¥Next, install Prisma ORM's driver adapter for pg
:
npm install @prisma/adapter-pg
3. 使用驱动适配器实例化 Prisma Client
¥ Instantiate Prisma Client using the driver adapter
最后,当实例化 Prisma Client 时,需要将 Prisma ORM 的驱动适配器的实例传递给 PrismaClient
构造函数:
¥Finally, when you instantiate Prisma Client, you need to pass an instance of Prisma ORM's driver adapter to the PrismaClient
constructor:
import { PrismaPg } from '@prisma/adapter-pg'
import { PrismaClient } from '@prisma/client'
const connectionString = `${process.env.DATABASE_URL}`
const adapter = new PrismaPg({ connectionString });
const prisma = new PrismaClient({ adapter });
请注意,此代码需要将 DATABASE_URL
环境变量设置为 PostgreSQL 连接字符串。你可以在下面了解有关连接字符串的更多信息。
¥Notice that this code requires the DATABASE_URL
environment variable to be set to your PostgreSQL connection string. You can learn more about the connection string below.
注意
¥Notes
指定 PostgreSQL 模式
¥Specifying a PostgreSQL schema
你可以在实例化 PrismaPg
时通过传入 schema
选项来指定 PostgreSQL 模式:
¥You can specify a PostgreSQL schema by passing in the schema
option when instantiating PrismaPg
:
const adapter = new PrismaPg(
{ connectionString },
{ schema: 'myPostgresSchema' }
)
连接详情
¥Connection details
连接网址
¥Connection URL
Prisma ORM 遵循 PostgreSQL 的官方指南 指定的连接 URL 格式,但不支持所有参数,并包含 schema
等附加参数。以下是 PostgreSQL 连接 URL 所需组件的概述:
¥Prisma ORM follows the connection URL format specified by PostgreSQL's official guidelines, but does not support all arguments and includes additional arguments such as schema
. Here's an overview of the components needed for a PostgreSQL connection URL:
基本 URL 和路径
¥Base URL and path
以下是使用大写字母占位符值的基本 URL 和路径的结构示例:
¥Here is an example of the structure of the base URL and the path using placeholder values in uppercase letters:
postgresql://USER:PASSWORD@HOST:PORT/DATABASE
以下组件构成数据库的基本 URL,它们始终是必需的:
¥The following components make up the base URL of your database, they are always required:
名称 | 占位符 | 描述 |
---|---|---|
主持人 | HOST | 你的数据库服务器的 IP 地址/域,例如 localhost |
港口 | PORT | 数据库服务器运行的端口,例如 5432 |
用户 | USER | 你的数据库用户的名称,例如 janedoe |
密码 | PASSWORD | 你的数据库用户的密码 |
数据库 | DATABASE | 你要使用的 database 的名称,例如 mydb |
你必须 对特殊字符进行百分比编码。
¥You must percentage-encode special characters.
参数
¥Arguments
连接 URL 也可以带参数。以下是与上面相同的示例,其中三个参数的占位符值均采用大写字母:
¥A connection URL can also take arguments. Here is the same example from above with placeholder values in uppercase letters for three arguments:
postgresql://USER:PASSWORD@HOST:PORT/DATABASE?KEY1=VALUE&KEY2=VALUE&KEY3=VALUE
可以使用以下参数:
¥The following arguments can be used:
参数名称 | 必需的 | 默认 | 描述 |
---|---|---|---|
schema | 是的 | public | 你要使用的 schema 的名称,例如 myschema |
connection_limit | 不 | num_cpus * 2 + 1 | 连接池 的最大尺寸 |
connect_timeout | 不 | 5 | 等待新连接打开的最大秒数,0 表示不超时 |
pool_timeout | 不 | 10 | 等待池中新连接的最大秒数,0 表示不超时 |
sslmode | 不 | prefer | 配置是否使用 TLS。可能的值:prefer 、disable 、require |
sslcert | 不 | 服务器证书的路径。证书路径为 相对于 ./prisma folder 已解决 | |
sslrootcert | 不 | 根证书的路径。证书路径为 相对于 ./prisma folder 已解决 | |
sslidentity | 不 | PKCS12 证书的路径 | |
sslpassword | 不 | 用于保护 PKCS12 文件的密码 | |
sslaccept | 不 | accept_invalid_certs | 配置是否检查证书中的缺失值。可能的值:accept_invalid_certs 、strict |
host | 不 | 指向包含用于连接的套接字的目录 | |
socket_timeout | 不 | 等待单个查询终止的最大秒数 | |
pgbouncer | 不 | false | 将引擎配置为 启用 PgBouncer 兼容模式 |
statement_cache_size | 不 | 100 | 自 2.1.0 起:指定每个连接缓存的 准备好的陈述 数量 |
application_name | 不 | 自 3.3.0 起:指定 application_name 配置参数的值 | |
channel_binding | 不 | prefer | 从 4.8.0 开始:指定 channel_binding 配置参数的值 |
options | 不 | 从 3.8.0 开始:指定在连接启动时发送到服务器的命令行选项 |
例如,如果要连接到名为 myschema
的架构,请将连接池大小设置为 5
并配置查询超时为 3
秒。你可以使用以下参数:
¥As an example, if you want to connect to a schema called myschema
, set the connection pool size to 5
and configure a timeout for queries of 3
seconds. You can use the following arguments:
postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=myschema&connection_limit=5&socket_timeout=3
配置 SSL 连接
¥Configuring an SSL connection
如果你的数据库服务器使用 SSL,则可以向连接 URL 添加各种参数。以下是可能参数的概述:
¥You can add various parameters to the connection URL if your database server uses SSL. Here's an overview of the possible parameters:
-
sslmode=(disable|prefer|require)
:-
prefer
(默认):如果可能,首选 TLS,接受纯文本连接。¥
prefer
(default): Prefer TLS if possible, accept plain text connections. -
disable
:不要使用 TLS。¥
disable
: Do not use TLS. -
require
:需要 TLS,否则失败。¥
require
: Require TLS or fail if not possible.
-
-
sslcert=<PATH>
:服务器证书的路径。这是数据库服务器用来签署客户端证书的根证书。如果系统的受信任证书存储中不存在该证书,则需要提供此证书。对于 Google Cloud,这可能是server-ca.pem
。证书路径为 相对于./prisma folder
已解决¥
sslcert=<PATH>
: Path to the server certificate. This is the root certificate used by the database server to sign the client certificate. You need to provide this if the certificate doesn't exist in the trusted certificate store of your system. For Google Cloud this likely isserver-ca.pem
. Certificate paths are resolved relative to the./prisma folder
-
sslidentity=<PATH>
:从客户端证书和密钥创建的 PKCS12 证书数据库的路径。这是 PKCS12 格式的 SSL 身份文件,你将使用客户端密钥和客户端证书生成该文件。它将这两个文件组合在一个文件中,并通过密码保护它们(请参阅下一个参数)。你可以使用以下命令(使用openssl
)使用客户端密钥和客户端证书创建此文件:¥
sslidentity=<PATH>
: Path to the PKCS12 certificate database created from client cert and key. This is the SSL identity file in PKCS12 format which you will generate using the client key and client certificate. It combines these two files in a single file and secures them via a password (see next parameter). You can create this file using your client key and client certificate by using the following command (usingopenssl
):openssl pkcs12 -export -out client-identity.p12 -inkey client-key.pem -in client-cert.pem
-
sslpassword=<PASSWORD>
:用于保护 PKCS12 文件的密码。上一步中列出的openssl
命令将在创建 PKCS12 文件时要求输入密码,你需要在此处提供完全相同的密码。¥
sslpassword=<PASSWORD>
: Password that was used to secure the PKCS12 file. Theopenssl
command listed in the previous step will ask for a password while creating the PKCS12 file, you will need to provide that same exact password here. -
sslaccept=(strict|accept_invalid_certs)
:-
strict
:证书中的任何缺失值都会导致错误。对于 Google Cloud,特别是如果数据库没有域名,证书可能会丢失域名/IP 地址,从而导致连接时出错。¥
strict
: Any missing value in the certificate will lead to an error. For Google Cloud, especially if the database doesn't have a domain name, the certificate might miss the domain/IP address, causing an error when connecting. -
accept_invalid_certs
(默认):绕过这个检查。请注意此设置的安全后果。¥
accept_invalid_certs
(default): Bypass this check. Be aware of the security consequences of this setting.
-
你的数据库连接 URL 将类似于以下内容:
¥Your database connection URL will look similar to this:
postgresql://USER:PASSWORD@HOST:PORT/DATABASE?sslidentity=client-identity.p12&sslpassword=mypassword&sslcert=rootca.cert
通过套接字连接
¥Connecting via sockets
要通过套接字连接到 PostgreSQL 数据库,你必须将 host
字段作为查询参数添加到连接 URL(而不是将其设置为 URI 的 host
部分)。该参数的值必须指向包含套接字的目录,例如:postgresql://USER:PASSWORD@localhost/database?host=/var/run/postgresql/
¥To connect to your PostgreSQL database via sockets, you must add a host
field as a query parameter to the connection URL (instead of setting it as the host
part of the URI).
The value of this parameter then must point to the directory that contains the socket, e.g.: postgresql://USER:PASSWORD@localhost/database?host=/var/run/postgresql/
请注意,localhost
是必需的,该值本身将被忽略并且可以是任何值。
¥Note that localhost
is required, the value itself is ignored and can be anything.
注意:你可以在此 GitHub 问题 中找到更多上下文。
¥Note: You can find additional context in this GitHub issue.
PostgreSQL 和 Prisma 模式之间的类型映射
¥Type mapping between PostgreSQL and Prisma schema
这两个表显示了 PostgreSQL 和 Prisma 模式之间的类型映射。首先是 Prisma ORM 标量类型如何转换为 PostgreSQL 数据库列类型,然后是 PostgreSQL 数据库列类型如何与 Prisma ORM 标量和原生类型相关。
¥These two tables show the type mapping between PostgreSQL and Prisma schema. First how Prisma ORM scalar types are translated into PostgreSQL database column types, and then how PostgreSQL database column types relate to Prisma ORM scalar and native types.
或者,请参阅 Prisma 架构参考 了解按 Prisma 类型组织的类型映射。
¥Alternatively, see Prisma schema reference for type mappings organized by Prisma type.
Prisma ORM 标量类型和 PostgreSQL 数据库列类型之间的映射
¥Mapping between Prisma ORM scalar types and PostgreSQL database column types
PostgreSQL 连接器将 Prisma ORM 数据模型 中的 标量类型 映射到数据库列类型,如下所示:
¥The PostgreSQL connector maps the scalar types from the Prisma ORM data model as follows to database column types:
Prisma ORM | PostgreSQL |
---|---|
String | text |
Boolean | boolean |
Int | integer |
BigInt | bigint |
Float | double precision |
Decimal | decimal(65,30) |
DateTime | timestamp(3) |
Json | jsonb |
Bytes | bytea |
PostgreSQL 数据库列类型到 Prisma ORM 标量和原生类型之间的映射
¥Mapping between PostgreSQL database column types to Prisma ORM scalar and native types
-
当 introspecting 是 PostgreSQL 数据库时,数据库类型根据下表映射到 Prisma ORM 类型。
¥When introspecting a PostgreSQL database, the database types are mapped to Prisma ORM types according to the following table.
-
当 创建迁移 或 构建你的架构原型 时,也使用该表 - 在另一个方向。
¥When creating a migration or prototyping your schema the table is also used - in the other direction.
PostgreSQL(类型 | 别名) | 支持的 | Prisma ORM | 原生数据库类型属性 | 注意 |
---|---|---|---|---|
bigint | int8 | ✔️ | BigInt | @db.BigInt * | *BigInt 的默认映射 - 没有类型属性添加到架构中。 |
boolean | bool | ✔️ | Bool | @db.Boolean * | *Bool 的默认映射 - 没有类型属性添加到架构中。 |
timestamp with time zone | timestamptz | ✔️ | DateTime | @db.Timestamptz(x) | |
time without time zone | time | ✔️ | DateTime | @db.Time(x) | |
time with time zone | timetz | ✔️ | DateTime | @db.Timetz(x) | |
numeric(p,s) | decimal(p,s) | ✔️ | Decimal | @db.Decimal(x, y) | |
real | float , float4 | ✔️ | Float | @db.Real | |
double precision | float8 | ✔️ | Float | @db.DoublePrecision * | *Float 的默认映射 - 没有类型属性添加到架构中。 |
smallint | int2 | ✔️ | Int | @db.SmallInt | |
integer | int , int4 | ✔️ | Int | @db.Int * | *Int 的默认映射 - 没有类型属性添加到架构中。 |
smallserial | serial2 | ✔️ | Int | @db.SmallInt @default(autoincrement()) | |
serial | serial4 | ✔️ | Int | @db.Int @default(autoincrement()) | |
bigserial | serial8 | ✔️ | Int | @db.BigInt @default(autoincrement() | |
character(n) | char(n) | ✔️ | String | @db.Char(x) | |
character varying(n) | varchar(n) | ✔️ | String | @db.VarChar(x) | |
money | ✔️ | Decimal | @db.Money | |
text | ✔️ | String | @db.Text * | *String 的默认映射 - 没有类型属性添加到架构中。 |
timestamp | ✔️ | DateTime | @db.TimeStamp * | *DateTime 的默认映射 - 没有类型属性添加到架构中。 |
date | ✔️ | DateTime | @db.Date | |
enum | ✔️ | Enum | 不适用 | |
inet | ✔️ | String | @db.Inet | |
bit(n) | ✔️ | String | @Bit(x) | |
bit varying(n) | ✔️ | String | @VarBit | |
oid | ✔️ | Int | @db.Oid | |
uuid | ✔️ | String | @db.Uuid | |
json | ✔️ | Json | @db.Json | |
jsonb | ✔️ | Json | @db.JsonB * | *Json 的默认映射 - 没有类型属性添加到架构中。 |
bytea | ✔️ | Bytes | @db.ByteA * | *Bytes 的默认映射 - 没有类型属性添加到架构中。 |
xml | ✔️ | String | @db.Xml | |
数组类型 | ✔️ | [] | ||
citext | ✔️ | String | @db.Citext | * 仅当 Citext 扩展已启用 时可用。 |
interval | 还没有 | Unsupported | ||
cidr | 还没有 | Unsupported | ||
macaddr | 还没有 | Unsupported | ||
tsvector | 还没有 | Unsupported | ||
tsquery | 还没有 | Unsupported | ||
int4range | 还没有 | Unsupported | ||
int8range | 还没有 | Unsupported | ||
numrange | 还没有 | Unsupported | ||
tsrange | 还没有 | Unsupported | ||
tstzrange | 还没有 | Unsupported | ||
daterange | 还没有 | Unsupported | ||
point | 还没有 | Unsupported | ||
line | 还没有 | Unsupported | ||
lseg | 还没有 | Unsupported | ||
box | 还没有 | Unsupported | ||
path | 还没有 | Unsupported | ||
polygon | 还没有 | Unsupported | ||
circle | 还没有 | Unsupported | ||
复合类型 | 还没有 | 不适用 | ||
域类型 | 还没有 | 不适用 |
内省 添加了 Unsupported
字段尚不支持的原生数据库类型:
¥Introspection adds native database types that are not yet supported as Unsupported
fields:
model Device {
id Int @id @default(autoincrement())
name String
data Unsupported("circle")
}
准备好的语句缓存
¥Prepared statement caching
准备好的声明 是一项可用于优化性能的功能。准备好的语句仅被解析、编译和优化一次,然后可以直接执行多次,而无需再次解析查询的开销。
¥A prepared statement is a feature that can be used to optimize performance. A prepared statement is parsed, compiled, and optimized only once and then can be executed directly multiple times without the overhead of parsing the query again.
通过缓存准备好的语句,Prisma Client 的 查询引擎 不会重复编译相同的查询,从而减少了数据库 CPU 使用率和查询延迟。
¥By caching prepared statements, Prisma Client's query engine does not repeatedly compile the same query which reduces database CPU usage and query latency.
例如,以下是 Prisma 客户端发送的两个不同查询生成的 SQL:
¥For example, here is the generated SQL for two different queries made by Prisma Client:
SELECT * FROM user WHERE name = "John";
SELECT * FROM user WHERE name = "Brenda";
参数化后的两个查询将是相同的,第二个查询可以跳过准备步骤,从而节省数据库 CPU 和与数据库的一次额外往返。参数化后查询:
¥The two queries after parameterization will be the same, and the second query can skip the preparing step, saving database CPU and one extra roundtrip to the database. Query after parameterization:
SELECT * FROM user WHERE name = $1
Prisma Client 维护的每个数据库连接都有一个单独的缓存,用于存储准备好的语句。可以使用连接字符串中的 statement_cache_size
参数调整此缓存的大小。默认情况下,Prisma Client 会为每个连接缓存 100
语句。
¥Every database connection maintained by Prisma Client has a separate cache for storing prepared statements. The size of this cache can be tweaked with the statement_cache_size
parameter in the connection string. By default, Prisma Client caches 100
statements per connection.
由于 pgBouncer 的性质,如果 pgbouncer
参数设置为 true
,则将自动禁用该连接的预准备语句缓存。
¥Due to the nature of pgBouncer, if the pgbouncer
parameter is set to true
, the prepared statement cache is automatically disabled for that connection.