部署到 Cloudflare Workers 和页面
本页面涵盖了使用 Prisma ORM 将应用部署到 Cloudflare Worker 或 Cloudflare 页面 所需了解的所有信息。
¥This page covers everything you need to know to deploy an app with Prisma ORM to a Cloudflare Worker or to Cloudflare Pages.
部署到 Cloudflare Workers 时的一般注意事项
¥General considerations when deploying to Cloudflare Workers
本部分涵盖了部署到 Cloudflare Workers 或 Pages 以及使用 Prisma ORM 时需要注意的一般事项,无论你使用哪个数据库提供商。
¥This section covers general things you need to be aware of when deploying to Cloudflare Workers or Pages and are using Prisma ORM, regardless of the database provider you use.
使用 Prisma Postgres
¥Using Prisma Postgres
你可以使用 Prisma Postgres 并部署到 Cloudflare Workers。
¥You can use Prisma Postgres and deploy to Cloudflare Workers.
创建 Worker 后,运行:
¥After you create a Worker, run:
npx prisma@latest init --db
输入项目名称并选择数据库区域。
¥Enter a name for your project and choose a database region.
这个命令:
¥This command:
-
将你的 CLI 连接到你的 账户。如果你未登录或没有账户,你的浏览器将打开以指导你创建新账户或登录现有账户。
¥Connects your CLI to your account. If you're not logged in or don't have an account, your browser will open to guide you through creating a new account or signing into your existing one.
-
为你的数据库模型创建一个包含
schema.prisma
文件的prisma
目录。¥Creates a
prisma
directory containing aschema.prisma
file for your database models. -
使用你的
DATABASE_URL
创建.env
文件(例如,对于 Prisma Postgres,它应该具有类似于DATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI..."
的内容)。¥Creates a
.env
file with yourDATABASE_URL
(e.g., for Prisma Postgres it should have something similar toDATABASE_URL="prisma+postgres://accelerate.prisma-data.net/?api_key=eyJhbGciOiJIUzI..."
).
你需要安装使用 Prisma Postgres 所需的客户端扩展:
¥You'll need to install the Client extension required to use Prisma Postgres:
npm i @prisma/extension-accelerate
并使用应用代码中的扩展扩展 PrismaClient
:
¥And extend PrismaClient
with the extension in your application code:
import { PrismaClient } from "@prisma/client/edge";
import { withAccelerate } from "@prisma/extension-accelerate";
export interface Env {
DATABASE_URL: string;
}
export default {
async fetch(request, env, ctx) {
const prisma = new PrismaClient({
datasourceUrl: env.DATABASE_URL,
}).$extends(withAccelerate());
const users = await prisma.user.findMany();
const result = JSON.stringify(users);
return new Response(result);
},
} satisfies ExportedHandler<Env>;
然后设置辅助脚本以执行迁移并将 PrismaClient
生成为 如本节所示。
¥Then setup helper scripts to perform migrations and generate PrismaClient
as shown in this section.
你需要安装 dotenv-cli
包,因为 Cloudflare Workers 不支持 .env
文件。你可以通过运行以下命令在项目中本地安装包来执行此操作:npm install -D dotenv-cli
。
¥You need to have the dotenv-cli
package installed as Cloudflare Workers does not support .env
files. You can do this by running the following command to install the package locally in your project: npm install -D dotenv-cli
.
使用边缘兼容驱动程序
¥Using an edge-compatible driver
部署使用 Prisma ORM 的 Cloudflare Worker 时,你需要为 Prisma ORM 使用 边缘兼容驱动程序 及其相应的 驱动适配器。
¥When deploying a Cloudflare Worker that uses Prisma ORM, you need to use an edge-compatible driver and its respective driver adapter for Prisma ORM.
Cloudflare Workers 和 Pages 的边缘兼容驱动程序包括:
¥The edge-compatible drivers for Cloudflare Workers and Pages are:
-
Neon 无服务器 使用 HTTP 访问数据库
¥Neon Serverless uses HTTP to access the database
-
PlanetScale 无服务器 使用 HTTP 访问数据库
¥PlanetScale Serverless uses HTTP to access the database
-
node-postgres
(pg
)使用 Cloudflare 的connect()
(TCP)访问数据库¥
node-postgres
(pg
) uses Cloudflare'sconnect()
(TCP) to access the database -
@libsql/client
用于通过 HTTP 访问 Turso 数据库¥
@libsql/client
is used to access Turso databases via HTTP -
Cloudflare D1 用于访问 D1 数据库
¥Cloudflare D1 is used to access D1 databases
node-mysql2
驱动程序上有 还有正在进行的工作,将来也可以从 Cloudflare Workers 和 Pages 访问传统 MySQL 数据库。
¥There's also work being done on the node-mysql2
driver which will enable access to traditional MySQL databases from Cloudflare Workers and Pages in the future as well.
如果你的应用使用 PostgreSQL,我们建议使用 Prisma Postgres。它完全支持边缘运行时,不需要专门的边缘兼容驱动程序。对于其他数据库,Prisma 加速 扩展了边缘兼容性,因此你可以从任何边缘函数提供商连接到任何数据库。
¥If your application uses PostgreSQL, we recommend using Prisma Postgres. It is fully supported on edge runtimes and does not require a specialized edge-compatible driver. For other databases, Prisma Accelerate extends edge compatibility so you can connect to any database from any edge function provider.
将数据库连接 URL 设置为环境变量
¥Setting your database connection URL as an environment variable
首先,确保在 Prisma 架构中将 DATABASE_URL
设置为 datasource
的 url
:
¥First, ensure that the DATABASE_URL
is set as the url
of the datasource
in your Prisma schema:
datasource db {
provider = "postgresql" // this might also be `mysql` or another value depending on your database
url = env("DATABASE_URL")
}
发展
¥Development
在开发中使用 Worker 时,你可以在本地通过 .dev.vars
文件 配置数据库连接。
¥When using your Worker in development, you can configure your database connection via the .dev.vars
file locally.
假设你使用上面的 DATABASE_URL
环境变量,你可以将其设置在 .dev.vars
中,如下所示:
¥Assuming you use the DATABASE_URL
environment variable from above, you can set it inside .dev.vars
as follows:
DATABASE_URL="your-database-connection-string"
在上面的代码片段中,your-database-connection-string
是一个占位符,你需要将其替换为你自己的连接字符串的值,例如:
¥In the above snippet, your-database-connection-string
is a placeholder that you need to replace with the value of your own connection string, for example:
DATABASE_URL="postgresql://admin:mypassword42@somehost.aws.com:5432/mydb"
请注意,.dev.vars
文件与 Prisma ORM 通常使用的 .env
文件不兼容。
¥Note that the .dev.vars
file is not compatible with .env
files which are typically used by Prisma ORM.
这意味着你需要确保 Prisma ORM 在需要时能够访问环境变量,例如 运行 Prisma CLI 命令(如 prisma migrate dev
)时。
¥This means that you need to make sure that Prisma ORM gets access to the environment variable when needed, e.g. when running a Prisma CLI command like prisma migrate dev
.
有多种选择可以实现此目的:
¥There are several options for achieving this:
-
使用
dotenv
运行 Prisma CLI 命令以指定 CLI 应从何处读取环境变量,例如:¥Run your Prisma CLI commands using
dotenv
to specify from where the CLI should read the environment variable, for example:dotenv -e .dev.vars -- npx prisma migrate dev
-
在
package.json
中创建一个脚本,通过dotenv
读取.dev.vars
。然后你可以执行prisma
命令,如下所示:npm run env -- npx prisma migrate dev
。这是该脚本的参考:¥Create a script in
package.json
that reads.dev.vars
viadotenv
. You can then executeprisma
commands as follows:npm run env -- npx prisma migrate dev
. Here's a reference for the script:package.json"scripts": { "env": "dotenv -e .dev.vars" }
-
将
DATABASE_URL
和任何其他相关环境变量复制到名为.env
的新文件中,然后 Prisma ORM 可以使用该文件。¥Duplicate the
DATABASE_URL
and any other relevant env vars into a new file called.env
which can then be used by Prisma ORM.
如果你使用的方法需要 dotenv
,则需要安装 dotenv-cli
软件包。你可以这样做,例如 使用以下命令在项目中本地安装包:npm install -D dotenv-cli
。
¥If you're using an approach that requires dotenv
, you need to have the dotenv-cli
package installed. You can do this e.g. by using this command to install the package locally in your project: npm install -D dotenv-cli
.
生产
¥Production
将 Worker 部署到生产环境时,你需要使用 wrangler
CLI 设置数据库连接:
¥When deploying your Worker to production, you'll need to set the database connection using the wrangler
CLI:
npx wrangler secret put DATABASE_URL
该命令是交互式的,将要求你在终端中输入 DATABASE_URL
环境变量的值作为下一步。
¥The command is interactive and will ask you to enter the value for the DATABASE_URL
env var as the next step in the terminal.
此命令要求你进行身份验证,如果你未通过身份验证,则会要求你登录 Cloudflare 账户。
¥This command requires you to be authenticated, and will ask you to log in to your Cloudflare account in case you are not.
免费账户的大小限制
¥Size limits on free accounts
Cloudflare 有 免费计划中 Workers 的大小限制为 3 MB。如果你的 Prisma ORM 应用包超过该大小,我们建议升级到付费 Worker 计划或使用 Prisma Accelerate 来部署你的应用。
¥Cloudflare has a size limit of 3 MB for Workers on the free plan. If your application bundle with Prisma ORM exceeds that size, we recommend upgrading to a paid Worker plan or using Prisma Accelerate to deploy your application.
使用 @cloudflare/next-on-pages
将 Next.js 应用部署到 Cloudflare Pages
¥Deploying a Next.js app to Cloudflare Pages with @cloudflare/next-on-pages
Cloudflare 提供了使用 @cloudflare/next-on-pages
在 Cloudflare Pages 上运行 Next.js 应用的选项,请参阅 docs 了解说明。
¥Cloudflare offers an option to run Next.js apps on Cloudflare Pages with @cloudflare/next-on-pages
, see the docs for instructions.
根据一些测试,我们发现以下内容:
¥Based on some testing, we found the following:
-
你可以使用 PlanetScale 或 Neon Serverless Driver 进行部署。
¥You can deploy using the PlanetScale or Neon Serverless Driver.
-
使用
pg
的传统 PostgreSQL 部署不起作用,因为pg
本身当前无法与@cloudflare/next-on-pages
一起使用(请参阅 此处)。¥Traditional PostgreSQL deployments using
pg
don't work becausepg
itself currently does not work with@cloudflare/next-on-pages
(see here).
如果你发现这方面有任何变化,请随时通过 Discord 与我们联系。
¥Feel free to reach out to us on Discord if you find that anything has changed about this.
使用 node
本地运行时设置 PRISMA_CLIENT_FORCE_WASM=1
¥Set PRISMA_CLIENT_FORCE_WASM=1
when running locally with node
一些框架(例如 hono)使用 node
而不是 wrangler
在本地运行 Workers。如果你正在使用这样的框架或出于其他原因使用 node
在本地运行 Worker,则需要设置 PRISMA_CLIENT_FORCE_WASM
环境变量:
¥Some frameworks (e.g. hono) use node
instead of wrangler
for running Workers locally. If you're using such a framework or are running your Worker locally with node
for another reason, you need to set the PRISMA_CLIENT_FORCE_WASM
environment variable:
export PRISMA_CLIENT_FORCE_WASM=1
特定于数据库的注意事项和示例
¥Database-specific considerations & examples
本部分提供有关使用 Prisma ORM 部署 Cloudflare Worker 的特定于数据库的说明。
¥This section provides database-specific instructions for deploying a Cloudflare Worker with Prisma ORM.
先决条件
¥Prerequisites
作为以下部分的先决条件,你需要在本地运行 Cloudflare Worker 并安装 Prisma CLI。
¥As a prerequisite for the following section, you need to have a Cloudflare Worker running locally and the Prisma CLI installed.
如果你还没有,你可以运行以下命令:
¥If you don't have that yet, you can run these commands:
npm create cloudflare@latest prisma-cloudflare-worker-example -- --type hello-world
cd prisma-cloudflare-worker-example
npm install prisma --save-dev && npm install @prisma/client
npx prisma init --output ../generated/prisma
你还需要你选择的数据库提供程序的可用数据库实例。请参阅提供商的相应文档来设置该实例。
¥You'll further need a database instance of your database provider of choice available. Refer to the respective documentation of the provider for setting up that instance.
我们将在下面的示例中使用默认的 User
模型:
¥We'll use the default User
model for the example below:
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
PostgreSQL(传统)
¥PostgreSQL (traditional)
如果你使用的是通过 TCP 和 pg
驱动程序访问的传统 PostgreSQL 数据库,你需要:
¥If you are using a traditional PostgreSQL database that's accessed via TCP and the pg
driver, you need to:
-
使用
@prisma/adapter-pg
数据库适配器(通过driverAdapters
预览功能)¥use the
@prisma/adapter-pg
database adapter (via thedriverAdapters
Preview feature) -
将
node_compat = true
设置为wrangler.toml
(参见 Cloudflare 文档)¥set
node_compat = true
inwrangler.toml
(see the Cloudflare docs)
1. 配置 Prisma 架构和数据库连接
¥ Configure Prisma schema & database connection
如果你没有要部署的项目,请按照 先决条件 中的说明引导包含 Prisma ORM 的基本 Cloudflare Worker。
¥If you don't have a project to deploy, follow the instructions in the Prerequisites to bootstrap a basic Cloudflare Worker with Prisma ORM in it.
首先,确保数据库连接配置正确。在 Prisma 架构中,将 datasource
块的 url
设置为 DATABASE_URL
环境变量。你还需要启用 driverAdapters
功能标志:
¥First, ensure that the database connection is configured properly. In your Prisma schema, set the url
of the datasource
block to the DATABASE_URL
environment variable. You also need to enable the driverAdapters
feature flag:
generator client {
provider = "prisma-client-js"
previewFeatures = ["driverAdapters"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
接下来,你需要将 DATABASE_URL
环境变量设置为数据库连接字符串的值。你将在 Cloudflare 使用的名为 .dev.vars
的文件中执行此操作:
¥Next, you need to set the DATABASE_URL
environment variable to the value of your database connection string. You'll do this in a file called .dev.vars
used by Cloudflare:
DATABASE_URL="postgresql://admin:mypassword42@somehost.aws.com:5432/mydb"
由于 Prisma CLI 默认情况下仅与 .env
文件兼容,因此你可以使用以下脚本调整 package.json
,该脚本从 .dev.vars
加载环境变量。然后,你可以在执行 prisma
命令之前使用此脚本加载环境变量。
¥Because the Prisma CLI by default is only compatible with .env
files, you can adjust your package.json
with the following script that loads the env vars from .dev.vars
. You can then use this script to load the env vars before executing a prisma
command.
将此脚本添加到你的 package.json
:
¥Add this script to your package.json
:
{
// ...
"scripts": {
// ....
"env": "dotenv -e .dev.vars"
},
// ...
}
现在你可以按如下方式执行 Prisma CLI 命令,同时确保该命令有权访问 .dev.vars
中的环境变量:
¥Now you can execute Prisma CLI commands as follows while ensuring that the command has access to the env vars in .dev.vars
:
npm run env -- npx prisma
2. 安装依赖
¥ Install dependencies
接下来,安装所需的软件包:
¥Next, install the required packages:
npm install @prisma/adapter-pg
3. 将 node_compat = true
设置为 wrangler.toml
¥ Set node_compat = true
in wrangler.toml
在 wrangler.toml
文件中,添加以下行:
¥In your wrangler.toml
file, add the following line:
node_compat = true
4. 迁移你的数据库架构(如果适用)
¥ Migrate your database schema (if applicable)
如果你运行了上面的 npx prisma init
,则需要迁移数据库架构以创建 Prisma 架构中定义的 User
表(如果你的数据库中已拥有所需的所有表,则可以跳过此步骤):
¥If you ran npx prisma init
above, you need to migrate your database schema to create the User
table that's defined in your Prisma schema (if you already have all the tables you need in your database, you can skip this step):
npm run env -- npx prisma migrate dev --name init
5. 在 Worker 中使用 Prisma 客户端向数据库发送查询
¥ Use Prisma Client in your Worker to send a query to the database
下面是一个示例代码片段,你可以使用它来实例化 PrismaClient
并向数据库发送查询:
¥Here is a sample code snippet that you can use to instantiate PrismaClient
and send a query to your database:
import { PrismaClient } from '@prisma/client'
import { PrismaPg } from '@prisma/adapter-pg'
export default {
async fetch(request, env, ctx) {
const adapter = new PrismaPg({ connectionString: env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
const users = await prisma.user.findMany()
const result = JSON.stringify(users)
return new Response(result)
},
}
6. 在本地运行 Worker
¥ Run the Worker locally
要在本地运行 Worker,你可以运行 wrangler dev
命令:
¥To run the Worker locally, you can run the wrangler dev
command:
npx wrangler dev
7. 设置 DATABASE_URL
环境变量并部署 Worker
¥ Set the DATABASE_URL
environment variable and deploy the Worker
要部署 Worker,首先需要 DATABASE_URL
环境变量 通过 wrangler
CLI:
¥To deploy the Worker, you first need to the DATABASE_URL
environment variable via the wrangler
CLI:
npx wrangler secret put DATABASE_URL
该命令是交互式的,将要求你在终端中输入 DATABASE_URL
环境变量的值作为下一步。
¥The command is interactive and will ask you to enter the value for the DATABASE_URL
env var as the next step in the terminal.
此命令要求你进行身份验证,如果你未通过身份验证,则会要求你登录 Cloudflare 账户。
¥This command requires you to be authenticated, and will ask you to log in to your Cloudflare account in case you are not.
然后你可以继续部署 Worker:
¥Then you can go ahead then deploy the Worker:
npx wrangler deploy
该命令将输出可以访问已部署 Worker 的 URL。
¥The command will output the URL where you can access the deployed Worker.
PlanetScale
如果你使用的是 PlanetScale 数据库,你需要:
¥If you are using a PlanetScale database, you need to:
-
使用
@prisma/adapter-planetscale
数据库适配器(通过driverAdapters
预览功能)¥use the
@prisma/adapter-planetscale
database adapter (via thedriverAdapters
Preview feature) -
手动删除冲突的
cache
字段:¥manually remove the conflicting
cache
field:export default {
async fetch(request, env, ctx) {
const adapter = new PrismaPlanetScale({
url: env.DATABASE_URL,
// see https://github.com/cloudflare/workerd/issues/698
fetch(url, init) {
delete init['cache']
return fetch(url, init)
},
})
const prisma = new PrismaClient({ adapter })
// ...
},
}
1. 配置 Prisma 架构和数据库连接
¥ Configure Prisma schema & database connection
如果你没有要部署的项目,请按照 先决条件 中的说明引导包含 Prisma ORM 的基本 Cloudflare Worker。
¥If you don't have a project to deploy, follow the instructions in the Prerequisites to bootstrap a basic Cloudflare Worker with Prisma ORM in it.
首先,确保数据库连接配置正确。在 Prisma 架构中,将 datasource
块的 url
设置为 DATABASE_URL
环境变量。你还需要启用 driverAdapters
功能标志:
¥First, ensure that the database connection is configured properly. In your Prisma schema, set the url
of the datasource
block to the DATABASE_URL
environment variable. You also need to enable the driverAdapters
feature flag:
generator client {
provider = "prisma-client-js"
previewFeatures = ["driverAdapters"]
}
datasource db {
provider = "mysql"
url = env("DATABASE_URL")
relationMode = "prisma" // required for PlanetScale (as by default foreign keys are disabled)
}
接下来,你需要将 DATABASE_URL
环境变量设置为数据库连接字符串的值。你将在 Cloudflare 使用的名为 .dev.vars
的文件中执行此操作:
¥Next, you need to set the DATABASE_URL
environment variable to the value of your database connection string. You'll do this in a file called .dev.vars
used by Cloudflare:
DATABASE_URL="mysql://32qxa2r7hfl3102wrccj:password@us-east.connect.psdb.cloud/demo-cf-worker-ps?sslaccept=strict"
由于 Prisma CLI 默认情况下仅与 .env
文件兼容,因此你可以使用以下脚本调整 package.json
,该脚本从 .dev.vars
加载环境变量。然后,你可以在执行 prisma
命令之前使用此脚本加载环境变量。
¥Because the Prisma CLI by default is only compatible with .env
files, you can adjust your package.json
with the following script that loads the env vars from .dev.vars
. You can then use this script to load the env vars before executing a prisma
command.
将此脚本添加到你的 package.json
:
¥Add this script to your package.json
:
{
// ...
"scripts": {
// ....
"env": "dotenv -e .dev.vars"
},
// ...
}
现在你可以按如下方式执行 Prisma CLI 命令,同时确保该命令有权访问 .dev.vars
中的环境变量:
¥Now you can execute Prisma CLI commands as follows while ensuring that the command has access to the env vars in .dev.vars
:
npm run env -- npx prisma
2. 安装依赖
¥ Install dependencies
接下来,安装所需的软件包:
¥Next, install the required packages:
npm install @prisma/adapter-planetscale
3. 迁移你的数据库架构(如果适用)
¥ Migrate your database schema (if applicable)
如果你运行了上面的 npx prisma init
,则需要迁移数据库架构以创建 Prisma 架构中定义的 User
表(如果你的数据库中已拥有所需的所有表,则可以跳过此步骤):
¥If you ran npx prisma init
above, you need to migrate your database schema to create the User
table that's defined in your Prisma schema (if you already have all the tables you need in your database, you can skip this step):
npm run env -- npx prisma db push
4. 在 Worker 中使用 Prisma 客户端向数据库发送查询
¥ Use Prisma Client in your Worker to send a query to the database
下面是一个示例代码片段,你可以使用它来实例化 PrismaClient
并向数据库发送查询:
¥Here is a sample code snippet that you can use to instantiate PrismaClient
and send a query to your database:
import { PrismaClient } from '@prisma/client'
import { PrismaPlanetScale } from '@prisma/adapter-planetscale'
export default {
async fetch(request, env, ctx) {
const adapter = new PrismaPlanetScale({
url: env.DATABASE_URL,
// see https://github.com/cloudflare/workerd/issues/698
fetch(url, init) {
delete init['cache']
return fetch(url, init)
},
})
const prisma = new PrismaClient({ adapter })
const users = await prisma.user.findMany()
const result = JSON.stringify(users)
return new Response(result)
},
}
6. 在本地运行 Worker
¥ Run the Worker locally
要在本地运行 Worker,你可以运行 wrangler dev
命令:
¥To run the Worker locally, you can run the wrangler dev
command:
npx wrangler dev
7. 设置 DATABASE_URL
环境变量并部署 Worker
¥ Set the DATABASE_URL
environment variable and deploy the Worker
要部署 Worker,首先需要 DATABASE_URL
环境变量 通过 wrangler
CLI:
¥To deploy the Worker, you first need to the DATABASE_URL
environment variable via the wrangler
CLI:
npx wrangler secret put DATABASE_URL
该命令是交互式的,将要求你在终端中输入 DATABASE_URL
环境变量的值作为下一步。
¥The command is interactive and will ask you to enter the value for the DATABASE_URL
env var as the next step in the terminal.
此命令要求你进行身份验证,如果你未通过身份验证,则会要求你登录 Cloudflare 账户。
¥This command requires you to be authenticated, and will ask you to log in to your Cloudflare account in case you are not.
然后你可以继续部署 Worker:
¥Then you can go ahead then deploy the Worker:
npx wrangler deploy
该命令将输出可以访问已部署 Worker 的 URL。
¥The command will output the URL where you can access the deployed Worker.
Neon
如果你使用的是 Neon 数据库,你需要:
¥If you are using a Neon database, you need to:
-
使用
@prisma/adapter-neon
数据库适配器(通过driverAdapters
预览功能)¥use the
@prisma/adapter-neon
database adapter (via thedriverAdapters
Preview feature)
1. 配置 Prisma 架构和数据库连接
¥ Configure Prisma schema & database connection
如果你没有要部署的项目,请按照 先决条件 中的说明引导包含 Prisma ORM 的基本 Cloudflare Worker。
¥If you don't have a project to deploy, follow the instructions in the Prerequisites to bootstrap a basic Cloudflare Worker with Prisma ORM in it.
首先,确保数据库连接配置正确。在 Prisma 架构中,将 datasource
块的 url
设置为 DATABASE_URL
环境变量。你还需要启用 driverAdapters
功能标志:
¥First, ensure that the database connection is configured properly. In your Prisma schema, set the url
of the datasource
block to the DATABASE_URL
environment variable. You also need to enable the driverAdapters
feature flag:
generator client {
provider = "prisma-client-js"
previewFeatures = ["driverAdapters"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
接下来,你需要将 DATABASE_URL
环境变量设置为数据库连接字符串的值。你将在 Cloudflare 使用的名为 .dev.vars
的文件中执行此操作:
¥Next, you need to set the DATABASE_URL
environment variable to the value of your database connection string. You'll do this in a file called .dev.vars
used by Cloudflare:
DATABASE_URL="postgresql://janedoe:password@ep-nameless-pond-a23b1mdz.eu-central-1.aws.neon.tech/neondb?sslmode=require"
由于 Prisma CLI 默认情况下仅与 .env
文件兼容,因此你可以使用以下脚本调整 package.json
,该脚本从 .dev.vars
加载环境变量。然后,你可以在执行 prisma
命令之前使用此脚本加载环境变量。
¥Because the Prisma CLI by default is only compatible with .env
files, you can adjust your package.json
with the following script that loads the env vars from .dev.vars
. You can then use this script to load the env vars before executing a prisma
command.
将此脚本添加到你的 package.json
:
¥Add this script to your package.json
:
{
// ...
"scripts": {
// ....
"env": "dotenv -e .dev.vars"
},
// ...
}
现在你可以按如下方式执行 Prisma CLI 命令,同时确保该命令有权访问 .dev.vars
中的环境变量:
¥Now you can execute Prisma CLI commands as follows while ensuring that the command has access to the env vars in .dev.vars
:
npm run env -- npx prisma
2. 安装依赖
¥ Install dependencies
接下来,安装所需的软件包:
¥Next, install the required packages:
npm install @prisma/adapter-neon
3. 迁移你的数据库架构(如果适用)
¥ Migrate your database schema (if applicable)
如果你运行了上面的 npx prisma init
,则需要迁移数据库架构以创建 Prisma 架构中定义的 User
表(如果你的数据库中已拥有所需的所有表,则可以跳过此步骤):
¥If you ran npx prisma init
above, you need to migrate your database schema to create the User
table that's defined in your Prisma schema (if you already have all the tables you need in your database, you can skip this step):
npm run env -- npx prisma migrate dev --name init
5. 在 Worker 中使用 Prisma 客户端向数据库发送查询
¥ Use Prisma Client in your Worker to send a query to the database
下面是一个示例代码片段,你可以使用它来实例化 PrismaClient
并向数据库发送查询:
¥Here is a sample code snippet that you can use to instantiate PrismaClient
and send a query to your database:
import { PrismaClient } from '@prisma/client'
import { PrismaNeon } from '@prisma/adapter-neon'
export default {
async fetch(request, env, ctx) {
const adapter = new PrismaNeon({ connectionString: env.DATABASE_URL })
const prisma = new PrismaClient({ adapter })
const users = await prisma.user.findMany()
const result = JSON.stringify(users)
return new Response(result)
},
}
6. 在本地运行 Worker
¥ Run the Worker locally
要在本地运行 Worker,你可以运行 wrangler dev
命令:
¥To run the Worker locally, you can run the wrangler dev
command:
npx wrangler dev
7. 设置 DATABASE_URL
环境变量并部署 Worker
¥ Set the DATABASE_URL
environment variable and deploy the Worker
要部署 Worker,首先需要 DATABASE_URL
环境变量 通过 wrangler
CLI:
¥To deploy the Worker, you first need to the DATABASE_URL
environment variable via the wrangler
CLI:
npx wrangler secret put DATABASE_URL
该命令是交互式的,将要求你在终端中输入 DATABASE_URL
环境变量的值作为下一步。
¥The command is interactive and will ask you to enter the value for the DATABASE_URL
env var as the next step in the terminal.
此命令要求你进行身份验证,如果你未通过身份验证,则会要求你登录 Cloudflare 账户。
¥This command requires you to be authenticated, and will ask you to log in to your Cloudflare account in case you are not.
然后你可以继续部署 Worker:
¥Then you can go ahead then deploy the Worker:
npx wrangler deploy
该命令将输出可以访问已部署 Worker 的 URL。
¥The command will output the URL where you can access the deployed Worker.