如何在 Cloudflare D1 中使用 Prisma ORM
介绍
¥Introduction
本指南将向你展示如何将 Prisma ORM 与 Cloudflare D1(一个在 Cloudflare 边缘网络上运行的无服务器 SQL 数据库)结合使用。你将学习如何使用 D1 设置 Prisma ORM、处理迁移,以及将你的应用部署到 Cloudflare Workers。你可以找到 GitHub 上的部署就绪示例。
¥This guide shows you how to use Prisma ORM with Cloudflare D1, a serverless SQL database that runs on Cloudflare's edge network. You'll learn how to set up Prisma ORM with D1, handle migrations, and deploy your application to Cloudflare Workers. You can find a deployment-ready example on GitHub.
先决条件
¥Prerequisites
在开始本指南之前,请确保你已准备好:
¥Before starting this guide, make sure you have:
-
Cloudflare 账户
¥A Cloudflare account
-
已安装 Node.js(版本 18 或更高版本)
¥Node.js installed (version 18 or higher)
-
已安装 Wrangler CLI(版本 3.39.0 或更高版本)
¥Wrangler CLI installed (version 3.39.0 or higher)
-
基本了解 Cloudflare Workers 和 D1
¥Basic familiarity with Cloudflare Workers and D1
1. 创建新的 Cloudflare Worker 并初始化 Prisma ORM
¥ Create a new Cloudflare Worker and initialize Prisma ORM
运行以下命令创建 新的 Cloudflare Worker 项目:
¥Run the following command to create a new Cloudflare Worker project:
npm create cloudflare@latest d1-tutorial -- --type=hello-world --ts=true --git=true --deploy=false
然后导航到新创建的目录:
¥Then navigate into the newly created directory:
cd d1-tutorial
并在项目中初始化 Prisma ORM:
¥And initialize Prisma ORM in the project:
npx prisma init --datasource-provider sqlite
并将 Prisma ORM CLI 安装为开发依赖:
¥And install the Prisma ORM CLI as a development dependency:
npm install --save-dev prisma
2. 配置 Prisma Schema
¥ Configure Prisma schema
在你的 Prisma 模式中,将 datasource
块的 provider
设置为 sqlite
。如果你刚刚使用 prisma init
引导 Prisma 模式,请务必向其中添加以下 User
模型:
¥In your Prisma schema, set the provider
of the datasource
to sqlite
. If you just bootstrapped the Prisma schema with prisma init
, also be sure to add the following User
model to it:
generator client {
provider = "prisma-client-js"
output = "../src/generated/prisma"
}
datasource db {
provider = "sqlite"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
3. 安装依赖
¥ Install dependencies
接下来,安装所需的软件包:
¥Next, install the required packages:
npm install @prisma/adapter-d1 dotenv
另外,请确保使用高于 wrangler@^3.39.0
版本的 Wrangler CLI,否则下一节中使用的 --remote
标志将不可用。
¥Also, be sure to use a version of the Wrangler CLI that's above wrangler@^3.39.0
, otherwise the --remote
flag that's used in the next sections won't be available.
4. 创建 D1 数据库
¥ Create a D1 database
运行以下命令创建新的 D1 数据库:
¥Run the following command to create a new D1 database:
npx wrangler@latest d1 create __YOUR_D1_DATABASE_NAME__
__YOUR_D1_DATABASE_NAME__
是一个占位符,应替换为你想要为 D1 数据库指定的名称。例如,你可以使用 prisma-d1-example
。
¥The __YOUR_D1_DATABASE_NAME__
is a placeholder that should be replaced with the name you want to give your D1 database. For example, you can use prisma-d1-example
.
此命令将通过 Cloudflare 对你进行身份验证,并要求你选择一个 Cloudflare 账户。之后,它将创建一个新的 D1 数据库并输出数据库 ID 和名称:
¥This command will authenticate you with Cloudflare and ask you to select a Cloudflare account. After that, it will create a new D1 database and output the database ID and name:
✅ Successfully created DB '__YOUR_D1_DATABASE_NAME__' in region __REGION__
Created your new D1 database.
{
"d1_databases": [
{
"binding": "DB",
"database_name": "__YOUR_D1_DATABASE_NAME__",
"database_id": "<unique-ID-for-your-database>"
}
]
}
复制终端输出并将内容添加到你的 wrangler.jsonc
文件中。此文件用于配置你的 Cloudflare Worker 及其绑定。
¥Copy the terminal output and add the content to your wrangler.jsonc
file. This file is used to configure your Cloudflare Worker and its bindings.
要将你的 Worker 与 D1 实例连接,请将以下绑定添加到你的 wrangler.jsonc
:
¥To connect your Workers with the D1 instance, add the following binding to your wrangler.jsonc
:
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "d1-tutorial",
"main": "src/index.ts",
"compatibility_date": "2025-08-05",
"d1_databases": [
{
"binding": "DB",
"database_name": "__YOUR_D1_DATABASE_NAME__", // to be replaced
"database_id": "__YOUR_D1_DATABASE_ID__" // to be replaced
}
]
}
上面代码片段中的 __YOUR_D1_DATABASE_NAME__
和 __YOUR_D1_DATABASE_ID__
是占位符,应替换为你自己的 D1 实例的数据库名称和 ID。
¥The __YOUR_D1_DATABASE_NAME__
and __YOUR_D1_DATABASE_ID__
in the snippet above are placeholders that should be replaced with the database name and ID of your own D1 instance.
如果你无法从终端输出中获取数据库 ID,你也可以在 Cloudflare 仪表板中或在终端中运行 npx wrangler d1 list
和 npx wrangler d1 info __YOUR_D1_DATABASE_NAME__
来获取它。
¥If you weren't able to grab the database ID from the terminal output, you can also find it in the Cloudflare Dashboard or by running npx wrangler d1 list
and npx wrangler d1 info __YOUR_D1_DATABASE_NAME__
in your terminal.
5. 设置数据库迁移
¥ Set up database migrations
我们建议使用 prisma migrate
以便迁移 D1 中的数据。但是,如果你更愿意使用 Cloudflare 的迁移系统 该工作流程是否可用
¥We recommend using prisma migrate
in order to keep your data in D1 migrated. However, if you would prefer to use Cloudflare's migration system, that workflow is also available
5.1 添加所需环境变量
¥5.1 Add needed environment variables
为了使用 Prisma D1 适配器,你需要向 .env
文件添加一些密钥信息:
¥In order to use the Prisma D1 adapter, you'll need to add a few secrets to a .env
file:
-
DATABASE_URL
:本地 D1 实例的路径。通常为"file:./prisma/db.sqlite"
。¥
DATABASE_URL
: A path to your local D1 instance. Usually"file:./prisma/db.sqlite"
. -
CLOUDFLARE_ACCOUNT_ID
:你的 Cloudflare 账户 ID,通过npx wrangler whoami
获取¥
CLOUDFLARE_ACCOUNT_ID
: Your Cloudflare account ID, fetched vianpx wrangler whoami
-
CLOUDFLARE_DATABASE_ID
:已检索数据库的 ID,在创建 D1 数据库期间。¥
CLOUDFLARE_DATABASE_ID
: The ID of your database, retrieved during D1 database creation. -
CLOUDFLARE_D1_TOKEN
:Prisma ORM 使用此 API 令牌直接与你的 D1 实例通信。要创建备份,请按照以下步骤操作:¥
CLOUDFLARE_D1_TOKEN
: This API token is used by Prisma ORM to communicate with your D1 instance directly. To create this, follow these steps:-
点击“"创建令牌"”
¥Click "Create Token"
-
在“自定义令牌”部分,点击“"立即开始"”。
¥On the Custom token section click on "Get started".
-
填写模板:请确保使用可识别的名称
¥Fill out the template: Make sure you use a recognizable name
-
对于权限,请添加
Account / D1 / Edit
权限。¥For the Permissions, add the
Account / D1 / Edit
permission. -
点击 "继续阅读摘要",然后点击 "创建令牌"。
¥Click "Continue to summary" and then "Create Token".
-
点击 "复制" 并将令牌存储在安全的地方。
¥Click on "Copy" and store the token in a safe place.
你现在可以存储这些密钥以供 Prisma ORM 使用。我们建议使用 .env
文件进行本地开发,但任何秘密存储都可以使用。
¥You can now store these secrets to be used by Prisma ORM. We recommend a .env
file for local development, but any secret store will work.
DATABASE_URL="file:./prisma/db.sqlite"
CLOUDFLARE_ACCOUNT_ID="0773..."
CLOUDFLARE_DATABASE_ID="01f30366-..."
CLOUDFLARE_D1_TOKEN="F8Cg..."
5.2 配置 Prisma 配置
¥5.2 Configure Prisma Config
确保在项目根目录中设置了 prisma.config.ts
文件,并定义了 驱动适配器。
¥Ensure that you have a prisma.config.ts
file set up in the root of your project with a driver adapter defined.
import type { PrismaConfig } from 'prisma';
import { PrismaD1 } from '@prisma/adapter-d1';
// import your .env file
import 'dotenv/config';
export default {
experimental: {
adapter: true,
},
schema: 'prisma/schema.prisma',
async adapter() {
return new PrismaD1({
CLOUDFLARE_D1_TOKEN: process.env.CLOUDFLARE_D1_TOKEN!,
CLOUDFLARE_ACCOUNT_ID: process.env.CLOUDFLARE_ACCOUNT_ID!,
CLOUDFLARE_DATABASE_ID: process.env.CLOUDFLARE_DATABASE_ID!,
});
},
} satisfies PrismaConfig;
从 Prisma ORM v6.11.0 开始,D1 适配器已从 PrismaD1HTTP
重命名为 PrismaD1
。
¥As of Prisma ORM v6.11.0, the D1 adapter has been renamed from PrismaD1HTTP
to PrismaD1
.
这将允许 prisma migrate
与你的 D1 数据库交互。
¥This will allow prisma migrate
to interact with your D1 database.
4.3 运行你的首次迁移
¥4.3 Run your first migration
你现在可以运行 prisma migrate dev
来迁移数据库以匹配你的本地模式:
¥You can now run prisma migrate dev
to migrate your database to match your local schema:
npx prisma migrate dev --name init
让我们创建一些虚拟数据,以便在 Worker 运行时查询。这次,我们将使用 wrangler 运行 SQL 语句,而不将其存储在文件中:
¥Let's also create some dummy data that we can query once the Worker is running. This time, we'll use wrangler to run a SQL statement without storing it in a file:
# For the local database
npx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command "INSERT INTO \"User\" (\"email\", \"name\") VALUES
('jane@prisma.io', 'Jane Doe (Local)');" --local
# For the remote database
npx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --command "INSERT INTO \"User\" (\"email\", \"name\") VALUES
('jane@prisma.io', 'Jane Doe (Remote)');" --remote
5. 实现 Worker
¥ Implement the Worker
在将 Prisma 客户端查询添加到你的 Worker 之前,你需要使用以下命令生成 Prisma 客户端:
¥Before adding a Prisma Client query to your Worker, you need to generate Prisma Client with the following command:
npx prisma generate
为了使用 Prisma ORM 从 Worker 查询数据库,你需要:
¥In order to query your database from the Worker using Prisma ORM, you need to:
-
将
DB
绑定添加到Env
接口。(或者,你可以运行npx wrangler types
,从名为worker-configuration.d.ts
的单独文件中的绑定生成Env
类型。)¥Add the
DB
binding to theEnv
interface. (Alternatively, you can runnpx wrangler types
to generate theEnv
type from the binding in a separate file calledworker-configuration.d.ts
.) -
使用
PrismaD1
驱动程序适配器实例化PrismaClient
。¥Instantiate
PrismaClient
using thePrismaD1
driver adapter. -
使用 Prisma 客户端发送查询并返回结果。
¥Send a query using Prisma Client and return the result.
打开 src/index.ts
文件并将其全部内容替换为以下内容:
¥Open src/index.ts
and replace the entire content with the following:
import { PrismaClient } from './generated/prisma/client';
import { PrismaD1 } from '@prisma/adapter-d1';
export interface Env {
DB: D1Database;
}
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
const adapter = new PrismaD1(env.DB);
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
首先将 .env
文件的内容复制到项目根目录中名为 .dev.vars
的新文件中。此文件将用于在本地运行 Worker 时设置环境变量。
¥First copy the contents of your .env
file to a new file called .dev.vars
in the root of your project. This file will be used to set environment variables when running the Worker locally.
cp .env .dev.vars
数据库查询到位并生成 Prisma 客户端后,你可以继续在本地运行 Worker:
¥With the database query in place and Prisma Client generated, you can go ahead and run the Worker locally:
npm run dev
现在,你可以打开浏览器访问 http://localhost:8787
查看数据库查询的结果:
¥Now you can open your browser at http://localhost:8787
to see the result of the database query:
;[{ id: 1, email: 'jane@prisma.io', name: 'Jane Doe (Local)' }]
7. 设置 DATABASE_URL
环境变量并部署 Worker
¥ Set the DATABASE_URL
environment variable and deploy the Worker
要部署 Worker,请运行以下命令:
¥To deploy the Worker, run the the following command:
npm run deploy
确保 将 .dev.vars
文件上传到你的 Cloudflare Worker 环境。此文件包含 Worker 连接到 D1 数据库所需的 DATABASE_URL
和其他环境变量。
¥Make sure to upload the .dev.vars
file to your Cloudflare Worker environment. This file contains the DATABASE_URL
and other environment variables needed for the Worker to connect to the D1 database.
你已部署的 Worker 可通过 https://prisma-d1-example.USERNAME.workers.dev
访问。如果你通过浏览器访问该 URL,你应该会看到从远程 D1 数据库查询到的以下数据:
¥Your deployed Worker is accessible via https://prisma-d1-example.USERNAME.workers.dev
. If you navigate your browser to that URL, you should see the following data that's queried from your remote D1 database:
;[{ id: 1, email: 'jane@prisma.io', name: 'Jane Doe (Remote)' }]
下一步
¥Next steps
现在你已经使用 Cloudflare D1 设置了 Prisma ORM,你可以:
¥Now that you've set up Prisma ORM with Cloudflare D1, you can:
-
使用 Prisma 强大的查询 API 添加更复杂的查询
¥Add more complex queries using Prisma's powerful query API
-
设置 Prisma Studio 进行数据库管理
¥Set up Prisma Studio for database management
-
实现数据库监控
¥Implement database monitoring
-
添加自动化测试
¥Add automated tests
更多信息:
¥For more information:
Stay connected with Prisma
Continue your Prisma journey by connecting with our active community. Stay informed, get involved, and collaborate with other developers:
- Follow us on X for announcements, live events and useful tips.
- Join our Discord to ask questions, talk to the community, and get active support through conversations.
- Subscribe on YouTube for tutorials, demos, and streams.
- Engage on GitHub by starring the repository, reporting issues, or contributing to an issue.