Skip to main content

如何在 Cloudflare D1 中使用 Prisma ORM

10 min

介绍

¥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(版本 20 或更高版本)

    ¥Node.js installed (version 20 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 schema,请确保将 runtime = "cloudflare" 添加到生成器块中,并添加以下 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 runtime = "cloudflare" to the generator block and the following User model:

prisma/schema.prisma
generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
runtime = "cloudflare"
}

datasource db {
provider = "sqlite"
}

model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}

3. 安装依赖

¥ Install dependencies

接下来,安装所需的软件包:

¥Next, install the required packages:

npm install @prisma/client @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:

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 listnpx 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

对于 Cloudflare D1,你将使用 Prisma 的迁移工作流结合 Wrangler CLI 来管理数据库架构。由于 D1 是一个无服务器 SQLite 数据库,我们将使用 prisma migrate diff 生成迁移 SQL,然后使用 Wrangler 应用它。

¥For Cloudflare D1, you'll use Prisma's migration workflow combined with Wrangler CLI to manage your database schema. Since D1 is a serverless SQLite database, we'll use prisma migrate diff to generate migration SQL and then apply it using Wrangler.

5.1 设置环境变量

¥5.1 Set up environment variables

在项目根目录下添加一个 .env 文件,并写入本地数据库 URL:

¥Add a .env file in the root of your project with your local database URL:

.env
DATABASE_URL="file:./prisma/db.sqlite"

此外,请在项目根目录中创建一个 prisma.config.ts 文件:

¥Also create a prisma.config.ts file in the root of your project:

prisma.config.ts
import 'dotenv/config';
import { defineConfig, env } from 'prisma/config';

export default defineConfig({
schema: 'prisma/schema.prisma',
migrations: {
path: 'prisma/migrations',
},
datasource: {
url: env('DATABASE_URL'),
},
});

5.2 生成迁移 SQL

¥5.2 Generate migration SQL

首先,在 prisma 文件夹内创建一个 migrations 目录,并创建一个名为 0001_init.sql 的文件:

¥First, create a migrations directory inside the prisma folder and create a file named 0001_init.sql:

mkdir -p prisma/migrations

现在使用 prisma migrate diff 生成创建数据库架构所需的 SQL:

¥Now use prisma migrate diff to generate the SQL needed to create your database schema:

npx prisma migrate diff \
--from-empty \
--to-schema prisma/schema.prisma \
--script > prisma/migrations/0001_init.sql

此命令生成一个包含创建数据库表所需语句的 SQL 文件。你可以在 prisma/migrations/0001_init.sql 中查看生成的 SQL。

¥This command generates a SQL file that contains the statements needed to create your database tables. You can inspect the generated SQL in prisma/migrations/0001_init.sql.

5.3 将迁移应用到 D1

¥5.3 Apply migrations to D1

现在使用 Wrangler 将迁移应用到本地和远程 D1 数据库:

¥Now apply the migration to both your local and remote D1 databases using Wrangler:

# Apply to local database
npx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --local --file=./prisma/migrations/0001_init.sql

# Apply to remote database
npx wrangler d1 execute __YOUR_D1_DATABASE_NAME__ --remote --file=./prisma/migrations/0001_init.sql
注意

__YOUR_D1_DATABASE_NAME__ 替换为你在步骤 4 中创建的 D1 数据库的实际名称。

¥Replace __YOUR_D1_DATABASE_NAME__ with the actual name of your D1 database that you created in step 4.

5.4 添加示例数据

¥5.4 Add sample data

让我们创建一些虚拟数据,以便在 Worker 运行时进行查询:

¥Let's create some dummy data that we can query once the Worker is running:

# 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
信息

对于未来的模式变更,你可以使用以下命令生成新的迁移文件:

¥For future schema changes, you can generate new migration files using:

npx prisma migrate diff \
--from-local-d1 \
--to-schema prisma/schema.prisma \
--script > migrations/0002_add_new_field.sql

然后使用与上面相同的 wrangler d1 execute 命令应用它们。

¥Then apply them using the same wrangler d1 execute commands as shown above.

6. 实现 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:

  1. DB 绑定添加到 Env 接口。此 DB 名称与你在 wrangler.jsonc 中配置的绑定名称匹配。(或者,你可以运行 npx wrangler types,从名为 worker-configuration.d.ts 的单独文件中的绑定生成 Env 类型。)

    ¥Add the DB binding to the Env interface. This DB name matches the binding name you configured in wrangler.jsonc. (Alternatively, you can run npx wrangler types to generate the Env type from the binding in a separate file called worker-configuration.d.ts.)

  2. 使用 PrismaD1 驱动程序适配器实例化 PrismaClient,并传递访问 D1 数据库绑定的 env.DB

    ¥Instantiate PrismaClient using the PrismaD1 driver adapter, passing env.DB which accesses your D1 database binding.

  3. 使用 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:

src/index.ts
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);
ctx.waitUntil(prisma.$disconnect()); // or just await prisma.$disconnect()
return new Response(result);
},
};

我们在此处显式调用 prisma.$disconnect(),以确保及时释放资源,否则 Worker 可能会耗尽内存。

¥We explicitly call prisma.$disconnect() here to guarantee timely release of resources or else the worker might run out of memory.

7. 在本地运行 Worker

¥ Run the Worker locally

数据库查询就绪并生成 Prisma 客户端后,你可以在本地运行 Worker。

¥With the database query in place and Prisma Client generated, you can run the Worker locally.

如果你的 Worker 需要任何环境变量,请在项目根目录中创建一个 .dev.vars 文件。在本例中,由于 wrangler.jsonc 中已配置了 D1 绑定,因此我们不需要任何额外的环境变量。

¥If your Worker needs any environment variables, create a .dev.vars file in the root of your project. For this example, we don't need any additional environment variables since the D1 binding is already configured in wrangler.jsonc.

现在在本地运行 Worker:

¥Now 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)' }]

8. 部署 Worker

¥ Deploy the Worker

要部署 Worker,请运行以下命令:

¥To deploy the Worker, run the following command:

npm run deploy

你已部署的 Worker 可通过 https://d1-tutorial.USERNAME.workers.dev 访问(将 USERNAME 替换为你的 Cloudflare 账户用户名)。如果你通过浏览器访问该 URL,你应该会看到从远程 D1 数据库查询到的以下数据:

¥Your deployed Worker is accessible via https://d1-tutorial.USERNAME.workers.dev (replace USERNAME with your Cloudflare account username). 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:

We genuinely value your involvement and look forward to having you as part of our community!