Cloudflare D1 存储
🌐 Cloudflare D1 Storage
Cloudflare D1 存储实现提供了一种无服务器的 SQL 数据库解决方案,使用 Cloudflare D1,支持关系操作和事务一致性。
🌐 The Cloudflare D1 storage implementation provides a serverless SQL database solution using Cloudflare D1, supporting relational operations and transactional consistency.
Cloudflare D1 storage does not support the observability domain. Traces from the DefaultExporter cannot be persisted to D1, and Mastra Studio's observability features won't work with D1 as your only storage provider. To enable observability, use composite storage to route observability data to a supported provider like ClickHouse or PostgreSQL.
Cloudflare D1 enforces a 1 MiB maximum row size. This limit can be exceeded when storing messages with base64-encoded attachments such as images. See Handling large attachments for workarounds including uploading attachments to external storage.
安装Direct link to 安装
🌐 Installation
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/cloudflare-d1@latest
pnpm add @mastra/cloudflare-d1@latest
yarn add @mastra/cloudflare-d1@latest
bun add @mastra/cloudflare-d1@latest
用法Direct link to 用法
🌐 Usage
在 Cloudflare Workers 上使用Direct link to 在 Cloudflare Workers 上使用
🌐 Using with Cloudflare Workers
在 Cloudflare Worker 中使用 D1Store 时,你需要在运行时通过 worker 的 env 参数访问 D1 绑定。你类型定义中的 D1Database 只是用于 TypeScript 类型检查——实际的绑定由 Workers 运行时提供。
🌐 When using D1Store in a Cloudflare Worker, you need to access the D1 binding from the worker's env parameter at runtime. The D1Database in your type definition is only for TypeScript type checking—the actual binding is provided by the Workers runtime.
import { D1Store } from "@mastra/cloudflare-d1";
import { Mastra } from "@mastra/core";
import { CloudflareDeployer } from "@mastra/deployer-cloudflare";
type Env = {
D1Database: D1Database; // TypeScript type definition
};
// Factory function to create Mastra with D1 binding
function createMastra(env: Env) {
const storage = new D1Store({
binding: env.D1Database, // ✅ Access the actual binding from env
tablePrefix: "dev_", // Optional: isolate tables per environment
});
return new Mastra({
storage,
deployer: new CloudflareDeployer({
name: "my-worker",
d1_databases: [
{
binding: "D1Database", // Must match the property name in Env type
database_name: "your-database-name",
database_id: "your-database-id"
}
],
}),
});
}
// Cloudflare Worker export
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
const mastra = createMastra(env);
// Your handler logic here
return new Response("Hello from Mastra with D1!");
}
};
In the Env type definition, D1Database: D1Database serves two purposes:
- 属性名称 (
D1Database) 必须与你的wrangler.toml中的binding名称匹配 - 类型 (
: D1Database) 来自@cloudflare/workers-types,用于 TypeScript 类型检查
在运行时,Cloudflare Workers 通过 env.D1Database 提供实际的 D1 数据库实例。你不能在 worker 的上下文之外直接使用 D1Database。
🌐 At runtime, Cloudflare Workers provides the actual D1 database instance via env.D1Database. You cannot use D1Database directly outside of the worker's context.
与 REST API 一起使用Direct link to 与 REST API 一起使用
🌐 Using with REST API
对于非 Worker 环境(Node.js、无服务器函数等),请使用 REST API 方法:
🌐 For non-Workers environments (Node.js, serverless functions, etc.), use the REST API approach:
import { D1Store } from "@mastra/cloudflare-d1";
const storage = new D1Store({
accountId: process.env.CLOUDFLARE_ACCOUNT_ID!, // Cloudflare Account ID
databaseId: process.env.CLOUDFLARE_D1_DATABASE_ID!, // D1 Database ID
apiToken: process.env.CLOUDFLARE_API_TOKEN!, // Cloudflare API Token
tablePrefix: "dev_", // Optional: isolate tables per environment
});
Wrangler 配置Direct link to Wrangler 配置
🌐 Wrangler Configuration
将 D1 数据库绑定添加到你的 wrangler.toml:
🌐 Add the D1 database binding to your wrangler.toml:
[[d1_databases]]
binding = "D1Database" # Must match the property name in your Env type
database_name = "your-database-name"
database_id = "your-database-id"
或者在 wrangler.jsonc 中:
🌐 Or in wrangler.jsonc:
{
"d1_databases": [
{
"binding": "D1Database",
"database_name": "your-database-name",
"database_id": "your-database-id"
}
]
}
参数Direct link to 参数
🌐 Parameters
binding?:
accountId?:
databaseId?:
apiToken?:
tablePrefix?:
附加说明Direct link to 附加说明
🌐 Additional Notes
模式管理Direct link to 模式管理
🌐 Schema Management
存储实现会自动处理模式的创建和更新。它会创建以下表格:
🌐 The storage implementation handles schema creation and updates automatically. It creates the following tables:
threads:存储对话线程messages:存储单条消息metadata:存储线程和消息的附加元数据
初始化Direct link to 初始化
🌐 Initialization
当你将存储传递给 Mastra 类时,init() 会在任何存储操作之前自动调用:
🌐 When you pass storage to the Mastra class, init() is called automatically before any storage operation:
import { Mastra } from "@mastra/core";
import { D1Store } from "@mastra/cloudflare-d1";
type Env = {
D1Database: D1Database;
};
// In a Cloudflare Worker
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
const storage = new D1Store({
binding: env.D1Database, // ✅ Use env.D1Database
});
const mastra = new Mastra({
storage, // init() is called automatically
});
// Your handler logic here
return new Response("Success");
}
};
如果你直接使用存储而不使用 Mastra,必须显式调用 init() 来创建表格:
🌐 If you're using storage directly without Mastra, you must call init() explicitly to create the tables:
import { D1Store } from "@mastra/cloudflare-d1";
type Env = {
D1Database: D1Database;
};
// In a Cloudflare Worker
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext) {
const storage = new D1Store({
id: 'd1-storage',
binding: env.D1Database, // ✅ Use env.D1Database
});
// Required when using storage directly
await storage.init();
// Access domain-specific stores via getStore()
const memoryStore = await storage.getStore('memory');
const thread = await memoryStore?.getThreadById({ threadId: "..." });
return new Response("Success");
}
};
如果未调用 init(),表将不会被创建,存储操作可能会静默失败或抛出错误。
事务与一致性Direct link to 事务与一致性
🌐 Transactions & Consistency
Cloudflare D1 为单行操作提供事务保证。这意味着可以将多个操作作为一个整体执行,要么全部成功,要么全部失败。
🌐 Cloudflare D1 provides transactional guarantees for single-row operations. This means that multiple operations can be executed as a single, all-or-nothing unit of work.
表创建与迁移Direct link to 表创建与迁移
🌐 Table Creation & Migrations
表在存储初始化时会自动创建(并且可以使用 tablePrefix 选项按环境隔离),但高级模式更改——例如添加列、更改数据类型或修改索引——需要手动迁移并小心规划以避免数据丢失。
🌐 Tables are created automatically when storage is initialized (and can be isolated per environment using the tablePrefix option), but advanced schema changes—such as adding columns, changing data types, or modifying indexes—require manual migration and careful planning to avoid data loss.