Skip to main content

Cloudflare D1

本页讨论了使用 Prisma ORM 和 Cloudflare D1 背后的概念,解释了 Cloudflare D1 与其他数据库提供商之间的共性和差异,并指导你完成配置应用以与 Cloudflare D1 集成的过程。

¥This page discusses the concepts behind using Prisma ORM and Cloudflare D1, explains the commonalities and differences between Cloudflare D1 and other database providers, and leads you through the process for configuring your application to integrate with Cloudflare D1.

对 Cloudflare D1 的 Prisma ORM 支持目前处于 预览 阶段。我们非常感谢你的反馈 在 GitHub 上

¥Prisma ORM support for Cloudflare D1 is currently in Preview. We would appreciate your feedback on GitHub.

如果你想使用 D1 和 Prisma ORM 部署 Cloudflare Worker,请遵循此 tutorial

¥If you want to deploy a Cloudflare Worker with D1 and Prisma ORM, follow this tutorial.

什么是 Cloudflare D1?

¥What is Cloudflare D1?

D1 是 Cloudflare 的原生无服务器数据库,最初是 2022 年推出。它基于 SQLite,可用于通过 Cloudflare Workers 部署应用。

¥D1 is Cloudflare's native serverless database and was initially launched in 2022. It's based on SQLite and can be used when deploying applications with Cloudflare Workers.

遵循 Cloudflare 的地理分布原则并使计算和数据更接近应用用户,D1 支持自动读取复制。它根据数据库从何处获取查询数量来动态管理数据库实例的数量和只读副本的位置。

¥Following Cloudflare's principles of geographic distribution and bringing compute and data closer to application users, D1 supports automatic read-replication. It dynamically manages the number of database instances and locations of read-only replicas based on how many queries a database is getting, and from where.

对于写入操作,查询会传输到单个主实例,以便将更改传播到所有读取副本并确保数据一致性。

¥For write-operations, queries travel to a single primary instance in order to propagate the changes to all read-replicas and ensure data consistency.

与其他数据库提供商的共同点

¥Commonalities with other database providers

D1 基于 SQLite。

¥D1 is based on SQLite.

将 Prisma ORM 与 D1 结合使用的许多方面就像将 Prisma ORM 与任何其他关系数据库结合使用一样。你仍然可以:

¥Many aspects of using Prisma ORM with D1 are just like using Prisma ORM with any other relational database. You can still:

需要考虑的差异

¥Differences to consider

D1 和 SQLite 之间有许多差异需要考虑。在决定使用 D1 和 Prisma ORM 时,你应该注意以下几点:

¥There are a number of differences between D1 and SQLite to consider. You should be aware of the following when deciding to use D1 and Prisma ORM:

  • 进行架构更改。从 v6.6.0 开始,你可以使用 prisma.config.ts 文件来使用 prisma db push。但是,如果你更喜欢 Cloudflare 优先的方法,则可以将 D1 的 迁移系统prisma migrate diff 命令用于迁移工作流程。有关更多信息,请参阅下面的 在 D1 上使用 Prisma ORM 进行 Schema 迁移 部分。

    ¥Making schema changes. As of v6.6.0 and with a prisma.config.ts file, you can use prisma db push. However, if you prefer a Cloudflare first approach, you can use D1's migration system and the prisma migrate diff command for your migration workflows. See the Schema migrations with Prisma ORM on D1 section below for more information.

  • 本地和远程 D1 (SQLite) 数据库。Cloudflare 提供 D1 的本地和远程版本。local 版本使用 wrangler d1 CLI 的 --local 选项进行管理,位于 .wrangler/state 中。remote 版本由 Cloudflare 管理,通过 HTTP 访问。

    ¥Local and remote D1 (SQLite) databases. Cloudflare provides local and remote versions of D1. The local version is managed using the --local option of the wrangler d1 CLI and is located in .wrangler/state. The remote version is managed by Cloudflare and is accessed via HTTP.

如何连接到 Cloudflare Workers 或 Cloudflare Pages 中的 D1

¥How to connect to D1 in Cloudflare Workers or Cloudflare Pages

当将 Prisma ORM 与 D1 结合使用时,你需要使用 sqlite 数据库提供程序和 @prisma/adapter-d1 驱动适配器

¥When using Prisma ORM with D1, you need to use the sqlite database provider and the @prisma/adapter-d1 driver adapter.

如果你想使用 D1 和 Prisma ORM 部署 Cloudflare Worker,请遵循这些 分步说明

¥If you want to deploy a Cloudflare Worker with D1 and Prisma ORM, follow these step-by-step instructions.

在 D1 上使用 Prisma ORM 进行 Schema 迁移

¥Schema migrations with Prisma ORM on D1

你可以使用两种方法通过 Prisma ORM 和 D1 迁移数据库架构:

¥You can use two approaches for migrating your database schema with Prisma ORM and D1:

  • prisma.config.ts 中通过驱动程序适配器使用 prisma db push

    ¥Using prisma db push via a driver adapter in prisma.config.ts

  • 使用 Wrangler CLI

    ¥Using the Wrangler CLI

prisma.config.ts 中通过驱动适配器使用 Prisma Migrate(抢先体验版)

¥Using Prisma Migrate via a driver adapter in prisma.config.ts (Early Access)

警告

此功能已在 抢先体验v6.6.0 中引入,并支持以下命令:

¥This functionality has been introduced in Early Access in v6.6.0 and supports the following commands:

  • prisma db push

  • prisma db pull

  • prisma migrate diff

其他命令,例如 prisma migrate devprisma migrate deploy,即将添加。

¥Other commands like prisma migrate dev and prisma migrate deploy will be added soon.

1. 安装 Prisma D1 驱动适配器

¥ Install the Prisma D1 driver adapter

在终端中运行此命令:

¥Run this command in your terminal:

npm install @prisma/adapter-d1

2. 设置环境变量

¥ Set environment variables

为了设置 D1 适配器,你需要向 .env 文件添加一些密钥:

¥In order to set up the D1 adapter, you'll need to add a few secrets to a .env file:

  • CLOUDFLARE_ACCOUNT_ID:你的 Cloudflare 账户 ID,通过 npx wrangler whoami 获取。

    ¥CLOUDFLARE_ACCOUNT_ID: Your Cloudflare account ID, fetched via npx wrangler whoami.

  • CLOUDFLARE_DATABASE_ID:在 D1 数据库创建期间检索。如果你已有 D1 数据库,则可以使用 npx wrangler d1 listnpx wrangler d1 info <database_name> 获取 ID。

    ¥CLOUDFLARE_DATABASE_ID: Retrieved during D1 database creation. If you have an existing D1 database, you can use npx wrangler d1 list and npx wrangler d1 info <database_name> to get the ID.

  • 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 it, follow these steps:

    1. 访问 https://dash.cloudflare.com/profile/api-tokens

      ¥Visit https://dash.cloudflare.com/profile/api-tokens

    2. 点击“创建令牌”

      ¥Click Create Token

    3. 点击“自定义令牌模板”

      ¥Click Custom token template

    4. 填写模板:确保使用可识别的名称并添加 Account / D1 / Edit 权限。

      ¥Fill out the template: Make sure you use a recognizable name and add the Account / D1 / Edit permission.

    5. 点击“继续查看摘要”,然后点击“创建令牌”。

      ¥Click Continue to summary and then Create Token.

然后,你可以将这些文件添加到你的 .env 文件中,或者如果它们存储在不同的密钥存储中,则直接使用它们:

¥You can then add these to your .env file or use them directly if they are stored in a different secret store:

.env
CLOUDFLARE_ACCOUNT_ID="0773..."
CLOUDFLARE_DATABASE_ID="01f30366-..."
CLOUDFLARE_D1_TOKEN="F8Cg..."

3. 设置 Prisma 配置文件

¥ Set up Prisma Config file

确保你的项目有一个 prisma.config.ts 文件。然后,设置 迁移驱动程序适配器 以引用 D1:

¥Make sure that you have a prisma.config.ts file for your project. Then, set up the migration driver adapter to reference D1:

prisma.config.ts
import path from 'node:path'
import type { PrismaConfig } from 'prisma'
import { PrismaD1HTTP } from '@prisma/adapter-d1'

// import your .env file
import 'dotenv/config'

type Env = {
CLOUDFLARE_D1_TOKEN: string
CLOUDFLARE_ACCOUNT_ID: string
CLOUDFLARE_DATABASE_ID: string
}

export default {
earlyAccess: true,
schema: path.join('prisma', 'schema.prisma'),

migrate: {
async adapter(env) {
return new PrismaD1HTTP({
CLOUDFLARE_D1_TOKEN: env.CLOUDFLARE_D1_TOKEN,
CLOUDFLARE_ACCOUNT_ID: env.CLOUDFLARE_ACCOUNT_ID,
CLOUDFLARE_DATABASE_ID: env.CLOUDFLARE_DATABASE_ID,
})
},
},
} satisfies PrismaConfig<Env>

4. 迁移数据库

¥ Migrate your database

Prisma Migrate 现在将根据 prisma.config.ts 中提供的配置针对你的远程 D1 数据库运行迁移。

¥Prisma Migrate now will run migrations against your remote D1 database based on the configuration provided in prisma.config.ts.

要使用此工作流更新远程模式,请运行以下命令:

¥To update the remote schema with this workflow, run the following command:

npx prisma db push
注意

请注意,查询数据库时,请继续使用 @prisma/adapter-d1 包中的 PrismaD1 驱动程序适配器:

¥Note that for querying the database, you keep using the PrismaD1 driver adapter from the @prisma/adapter-d1 package:

import { PrismaD1HTTP } from '@prisma/adapter-d1'

使用 Wrangler CLI

¥Using the Wrangler CLI

Cloudflare D1 带有自己的 迁移系统。虽然我们建议你使用 原生 Prisma Migrate 工作流,但你也可以通过 wrangler d1 migrations 命令使用此迁移系统。

¥Cloudflare D1 comes with its own migration system. While we recommend that you use the native Prisma Migrate workflow, this migration system via the wrangler d1 migrations command is available.

不过,此命令无法帮助你找出用于创建需要放入这些迁移文件中的数据库架构的 SQL 语句。如果你想使用 Prisma 客户端查询数据库,则数据库模式映射到 Prisma 模式非常重要,这就是为什么建议从 Prisma 模式生成 SQL 语句的原因。

¥This command doesn't help you in figuring out the SQL statements for creating your database schema that need to be put inside of these migration files though. If you want to query your database using Prisma Client, it's important that your database schema maps to your Prisma schema, this is why it's recommended to generate the SQL statements from your Prisma schema.

使用 D1 时,可以使用 prisma migrate diff 命令来实现此目的。

¥When using D1, you can use the prisma migrate diff command for that purpose.

创建初始迁移

¥Creating an initial migration

创建初始迁移的工作流程如下所示。假设你有一个没有任何表的新 D1 实例。

¥The workflow for creating an initial migration looks as follows. Assume you have a fresh D1 instance without any tables.

1. 更新你的 Prisma 数据模型

¥ Update your Prisma data model

这是你想要映射到 D1 实例的 Prisma 架构的初始版本:

¥This is your initial version of the Prisma schema that you want to map to your D1 instance:

model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
2. 使用 wrangler CLI 创建迁移文件

¥ Create migration file using wrangler CLI

接下来,你需要使用 wrangler d1 migrations create 命令创建迁移文件:

¥Next, you need to create the migration file using the wrangler d1 migrations create command:

npx wrangler d1 migrations create __YOUR_DATABASE_NAME__ create_user_table

由于这是第一次迁移,因此此命令将提示你还创建一个 migrations 文件夹。请注意,如果你希望将迁移文件存储在不同的位置,你可以 使用 Wrangler 进行自定义

¥Since this is the very first migration, this command will prompt you to also create a migrations folder. Note that if you want your migration files to be stored in a different location, you can customize it using Wrangler.

执行命令后,假设你为迁移文件的位置选择了默认的 migrations 名称,该命令将为你创建以下文件夹和文件:

¥Once the command has executed and assuming you have chosen the default migrations name for the location of your migration files, the command has created the following folder and file for you:

migrations/
└── 0001_create_user_table.sql

但是,在将迁移应用到 D1 实例之前,你实际上需要将 SQL 语句放入当前空的 0001_create_user_table.sql 文件中。

¥However, before you can apply the migration to your D1 instance, you actually need to put a SQL statement into the currently empty 0001_create_user_table.sql file.

3. 使用 prisma migrate diff 生成 SQL 语句

¥ Generate SQL statements using prisma migrate diff

要生成初始 SQL 语句,你可以使用 prisma migrate diff 命令,该命令与模式进行比较(通过其 --to-X--from-X 选项)并生成从一个模式到另一个模式的 "evolve" 所需的步骤。这些模式可以是 Prisma 或 SQL 模式。

¥To generate the initial SQL statement, you can use the prisma migrate diff command which compares to schemas (via its --to-X and --from-X options) and generates the steps that are needed to "evolve" from one to the other. These schemas can be either Prisma or SQL schemas.

对于初始迁移,你可以使用特殊的 --from-empty 选项:

¥For the initial migration, you can use the special --from-empty option though:

npx prisma migrate diff \
--from-empty \
--to-schema-datamodel ./prisma/schema.prisma \
--script \
--output migrations/0001_create_user_table.sql

上面的命令使用以下选项:

¥The command above uses the following options:

  • --from-empty:SQL 语句的源是一个空架构。

    ¥--from-empty: The source for the SQL statement is an empty schema.

  • --to-schema-datamodel ./prisma/schema.prisma:SQL 语句的目标是 ./prisma/schema.prisma 中的数据模型。

    ¥--to-schema-datamodel ./prisma/schema.prisma: The target for the SQL statement is the data model in ./prisma/schema.prisma.

  • --script:将结果输出为 SQL。如果省略此选项,"迁移步骤" 将以简单英语生成。

    ¥--script: Output the result as SQL. If you omit this option, the "migration steps" will be generated in plain English.

  • --output migrations/0001_create_user_table.sql:将结果存储在 migrations/0001_create_user_table.sql 中。

    ¥--output migrations/0001_create_user_table.sql: Store the result in migrations/0001_create_user_table.sql.

运行该命令后,migrations/0001_create_user_table.sql 将有以下内容:

¥After running this command, migrations/0001_create_user_table.sql will have the following contents:

migrations/0001_create_user_table.sql
-- CreateTable
CREATE TABLE "User" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"email" TEXT NOT NULL,
"name" TEXT
);

-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
4. 使用 wrangler d1 migrations apply 执行迁移

¥ Execute the migration using wrangler d1 migrations apply

最后,你可以对 D1 实例应用迁移。

¥Finally, you can apply the migration against your D1 instances.

对于本地实例,运行:

¥For the local instance, run:

npx wrangler d1 migrations apply __YOUR_DATABASE_NAME__ --local

对于远程实例,运行:

¥For the remote instance, run:

npx wrangler d1 migrations apply __YOUR_DATABASE_NAME__ --remote

通过进一步迁移来发展你的架构

¥Evolve your schema with further migrations

对于任何进一步的迁移,你可以使用相同的工作流程,但你需要使用 --from-local-d1,而不是使用 --from-empty,因为 prisma migrate diff 命令的源架构现在是该本地 D1 实例的当前架构,而目标仍然是你的(然后 更新)Prisma 架构。

¥For any further migrations, you can use the same workflow but instead of using --from-empty, you'll need to use --from-local-d1 because your source schema for the prisma migrate diff command now is the current schema of that local D1 instance, while the target remains your (then updated) Prisma schema.

1. 更新你的 Prisma 数据模型

¥ Update your Prisma data model

假设你已使用另一个模型更新了 Prisma 架构:

¥Assume you have updated your Prisma schema with another model:

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

model Post {
id Int @id @default(autoincrement())
title String
author User @relation(fields: [authorId], references: [id])
authorId Int
}
2. 使用 wrangler CLI 创建迁移文件

¥ Create migration file using wrangler CLI

和以前一样,你首先需要创建迁移文件:

¥Like before, you first need to create the migration file:

npx wrangler d1 migrations create __YOUR_DATABASE_NAME__ create_post_table

命令执行后(再次假设你为迁移文件的位置选择了默认的 migrations 名称),该命令会在 migrations 文件夹内创建一个新文件:

¥Once the command has executed (again assuming you have chosen the default migrations name for the location of your migration files), the command has created a new file inside of the migrations folder:

migrations/
├── 0001_create_user_table.sql
└── 0002_create_post_table.sql

和以前一样,你现在需要将 SQL 语句放入当前空的 0002_create_post_table.sql 文件中。

¥As before, you now need to put a SQL statement into the currently empty 0002_create_post_table.sql file.

3. 使用 prisma migrate diff 生成 SQL 语句

¥ Generate SQL statements using prisma migrate diff

如上所述,你现在需要使用 --from-local-d1 而不是 --from-empty 来指定源架构:

¥As explained above, you now need to use --from-local-d1 instead of --from-empty to specify a source schema:

npx prisma migrate diff \
--from-local-d1 \
--to-schema-datamodel ./prisma/schema.prisma \
--script \
--output migrations/0002_create_post_table.sql

上面的命令使用以下选项:

¥The command above uses the following options:

  • --from-local-d1:SQL 语句的来源是本地 D1 数据库文件。

    ¥--from-local-d1: The source for the SQL statement is the local D1 database file.

  • --to-schema-datamodel ./prisma/schema.prisma:SQL 语句的目标是 ./prisma/schema.prisma 中的数据模型。

    ¥--to-schema-datamodel ./prisma/schema.prisma: The target for the SQL statement is the data model in ./prisma/schema.prisma.

  • --script:将结果输出为 SQL。如果省略此选项,"迁移步骤" 将以简单英语生成。

    ¥--script: Output the result as SQL. If you omit this option, the "migration steps" will be generated in plain English.

  • --output migrations/0002_create_post_table.sql:将结果存储在 migrations/0002_create_post_table.sql 中。

    ¥--output migrations/0002_create_post_table.sql: Store the result in migrations/0002_create_post_table.sql.

运行该命令后,migrations/0002_create_post_table.sql 将有以下内容:

¥After running this command, migrations/0002_create_post_table.sql will have the following contents:

migrations/0002_create_post_table.sql
-- CreateTable
CREATE TABLE "Post" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"title" TEXT NOT NULL,
"authorId" INTEGER NOT NULL,
CONSTRAINT "Post_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
4. 使用 wrangler d1 migrations apply 执行迁移

¥ Execute the migration using wrangler d1 migrations apply

最后,你可以对 D1 实例应用迁移。

¥Finally, you can apply the migration against your D1 instances.

对于本地实例,运行:

¥For the local instance, run:

npx wrangler d1 migrations apply __YOUR_DATABASE_NAME__ --local

对于远程实例,运行:

¥For the remote instance, run:

npx wrangler d1 migrations apply __YOUR_DATABASE_NAME__ --remote

局限性

¥Limitations

不支持事务

¥Transactions not supported

Cloudflare D1 目前不支持事务(请参阅 打开功能请求)。因此,Prisma ORM 不支持 Cloudflare D1 的事务。使用 Prisma 的 D1 适配器时,隐式和显式事务将被忽略并作为单独的查询运行,这会破坏事务 ACID 属性的保证。

¥Cloudflare D1 currently does not support transactions (see the open feature request). As a result, Prisma ORM does not support transactions for Cloudflare D1. When using Prisma's D1 adapter, implicit & explicit transactions will be ignored and run as individual queries, which breaks the guarantees of the ACID properties of transactions.

Prisma Migrate 仅支持远程 D1 数据库

¥Prisma Migrate only supports remote D1 databases

Wrangler CLI 可以通过 --local--remote 选项区分本地和远程 D1(即 SQLite)数据库实例。此区别目前在 原生 Prisma Migrate 工作流 中不可用。

¥The Wrangler CLI can distinguish between local and remote D1 (i.e. SQLite) database instances via the --local and --remote options. This distinction is currently not available with the native Prisma Migrate workflow.