@drizzle-adapter/d1

中文文档
2.0.1发布于 2026/11/07MITTypeScriptES Module近 30 天下载 2.1万

Cloudflare D1 adapter implementation for the Drizzle Adapter ecosystem.

原始使用文档
文档目录20 节
  1. Overview
  2. Why D1?
  3. Perfect For:
  4. Installation
  5. Important: Adapter Registration
  6. D1 Compatibility Layer
  7. Execute Method Mapping
  8. Transaction Compatibility
  9. Migration Considerations
  10. Releasing
  11. Usage
  12. Cloudflare Workers Setup
  13. Configuration
  14. Important Note About Connections
  15. Schema Definition
  16. Basic CRUD Operations
  17. Worker Implementation
  18. Best Practices
  19. Contributing
  20. Related Packages

@drizzle-adapter/d1

Cloudflare D1 adapter implementation for the Drizzle Adapter ecosystem.

Overview

The @drizzle-adapter/d1 package provides the Cloudflare D1 implementation for the Drizzle Adapter interface. While you don't interact with this package directly (you use @drizzle-adapter/core instead), it enables D1 support in the Drizzle Adapter ecosystem.

Why D1?

D1 offers unique advantages for Cloudflare Workers:

  • Edge SQLite: Distributed SQLite database built for the edge
  • Zero Configuration: Automatic replication and distribution
  • Global Performance: Data served from the closest edge location
  • Cloudflare Workers Integration: Native integration with Workers
  • Automatic Scaling: Built-in scalability and reliability
  • Cost Effective: Included in Workers pricing with generous free tier
  • SQLite Compatibility: Familiar SQLite interface and features
  • Automatic Backups: Built-in backup and restore capabilities

Perfect For:

  1. Edge Applications: Data served from the closest location
  2. Cloudflare Workers: Native database for Workers applications
  3. Global Applications: Automatic global distribution
  4. Cost-Sensitive Projects: Included in Workers pricing
  5. Simple Deployments: Zero configuration required

Installation

# Install both the core package and the D1 adapter
pnpm install @drizzle-adapter/core @drizzle-adapter/d1

Important: Adapter Registration

For the adapter to work correctly with the DrizzleAdapterFactory, you must import it for its self-registration side effects:

// Import for side effects - adapter will self-register
import '@drizzle-adapter/d1';

// Now you can use the factory
import { DrizzleAdapterFactory } from '@drizzle-adapter/core';

D1 Compatibility Layer

This adapter provides several compatibility enhancements to make D1 work seamlessly with existing Drizzle ORM code:

Execute Method Mapping

D1's Drizzle implementation uses run() instead of the standard execute() method. This adapter automatically maps execute() to run() for compatibility:

// Both of these work identically
await client.execute(sql`SELECT * FROM users`);
await client.run(sql`SELECT * FROM users`);

Transaction Compatibility

Breaking in 2.0.0: Cloudflare D1 has no interactive transactions. transaction() now throws D1TransactionUnsupportedError instead of running the callback without atomicity. The callback is never invoked.

import { D1TransactionUnsupportedError } from '@drizzle-adapter/d1';

try {
  await client.transaction(async (tx) => { /* never runs */ });
} catch (caughtError) {
  if (caughtError instanceof D1TransactionUnsupportedError) {
    // use db.batch() instead
  }
}

For atomic operations, use db.batch(). It runs as one implicit SQL transaction (all-or-nothing):

import { sql } from 'drizzle-orm';

const results = await client.batch([
  client.insert(users).values({ name: 'John' }),
  client.run(sql`UPDATE posts SET published = 1 WHERE id = ${postId}`)
]);

Migration Considerations

  • Transaction Compatibility: Since 2.0.0, db.transaction() throws D1TransactionUnsupportedError; migrate to db.batch()
  • No Rollback: Failed operations cannot be automatically rolled back
  • Batch Operations: Use db.batch() for operations that require atomicity
  • Error Handling: Implement manual cleanup logic for critical operations

Releasing

pnpm check && pnpm lint && pnpm test
pnpm --filter @drizzle-adapter/d1 publish --access public   # run from the repo root

Usage

Cloudflare Workers Setup

First, set up your D1 database:

# Create a new D1 database
wrangler d1 create my-database

# Add to wrangler.toml
[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "your-database-id"

Configuration

import { DrizzleAdapterFactory, TypeDrizzleDatabaseConfig } from '@drizzle-adapter/core';
import { D1Database } from '@cloudflare/workers-types';

interface Env {
  DB: D1Database;
}

const config: TypeDrizzleDatabaseConfig = {
  DATABASE_DRIVER: 'd1',
  DATABASE: env.DB
};

const factory = new DrizzleAdapterFactory();
const adapter = factory.create(config);

Important Note About Connections

While D1 operates within the Workers environment and doesn't require traditional database connections, this adapter implements the standard connection interface for compatibility. This means your code remains portable across different database adapters:

// These connection operations are no-ops for D1 but ensure
// your code remains portable if you switch to another database
const connection = await adapter.getConnection();

const client = connection.getClient();

// Your database operations

await connection.disconnect(); // No-op for D1

Schema Definition

const dataTypes = adapter.getDataTypes();

const users = dataTypes.dbTable('users', {
  id: dataTypes.dbInteger('id').primaryKey().autoincrement(),
  name: dataTypes.dbText('name').notNull(),
  email: dataTypes.dbText('email').notNull().unique(),
  metadata: dataTypes.dbText('metadata'), // JSON stored as text
  createdAt: dataTypes.dbInteger('created_at')
    .default(sql`(unixepoch())`)
});

const posts = dataTypes.dbTable('posts', {
  id: dataTypes.dbInteger('id').primaryKey().autoincrement(),
  userId: dataTypes.dbInteger('user_id')
    .references(() => users.id),
  title: dataTypes.dbText('title').notNull(),
  content: dataTypes.dbText('content').notNull(),
  published: dataTypes.dbInteger('published').default(0),
  createdAt: dataTypes.dbInteger('created_at')
    .default(sql`(unixepoch())`)
});

Basic CRUD Operations

import { eq, and, or, desc, sql } from 'drizzle-orm';

const client = await adapter.getConnection().getClient();

// INSERT
// Single insert with returning
const [newUser] = await client
  .insert(users)
  .values({
    name: 'John Doe',
    email: '[email protected]',
    metadata: JSON.stringify({ role: 'user' })
  })
  .returning();

// Bulk insert
await client
  .insert(posts)
  .values([
    {
      userId: newUser.id,
      title: 'First Post',
      content: 'Hello, world!'
    },
    {
      userId: newUser.id,
      title: 'Second Post',
      content: 'Another post'
    }
  ]);

// SELECT
// Select all
const allUsers = await client
  .select()
  .from(users);

// Select with conditions
const user = await client
  .select()
  .from(users)
  .where(eq(users.email, '[email protected]'));

// Select with join
const userPosts = await client
  .select({
    userName: users.name,
    postTitle: posts.title,
    content: posts.content,
    metadata: users.metadata
  })
  .from(posts)
  .leftJoin(users, eq(posts.userId, users.id))
  .where(eq(posts.published, 1))
  .orderBy(desc(posts.createdAt));

// UPDATE
await client
  .update(users)
  .set({
    name: 'John Smith',
    metadata: JSON.stringify({ role: 'admin' })
  })
  .where(eq(users.id, newUser.id));

// DELETE
await client
  .delete(posts)
  .where(
    and(
      eq(posts.userId, newUser.id),
      eq(posts.published, 0)
    )
  );

Worker Implementation

interface Env {
  DB: D1Database;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const factory = new DrizzleAdapterFactory();
    const adapter = factory.create({
      DATABASE_DRIVER: 'd1',
      DATABASE: env.DB
    });

    const client = await adapter.getConnection().getClient();
    const url = new URL(request.url);

    try {
      switch (url.pathname) {
        case '/users': {
          const users = await client
            .select()
            .from(users);
          return Response.json(users);
        }

        case '/posts': {
          const posts = await client
            .select({
              title: posts.title,
              content: posts.content,
              author: users.name
            })
            .from(posts)
            .leftJoin(users, eq(posts.userId, users.id))
            .where(eq(posts.published, 1))
            .orderBy(desc(posts.createdAt));
          return Response.json(posts);
        }

        default:
          return new Response('Not Found', { status: 404 });
      }
    } catch (error) {
      return new Response('Error', { status: 500 });
    }
  }
}

Best Practices

  1. Edge Optimization: Queries are automatically optimized for edge execution
  2. JSON Handling: Store JSON data as TEXT and parse/stringify as needed
  3. Error Handling: Implement proper error handling for edge environments
  4. Query Optimization: Minimize the number of queries per request
  5. Portability: Use the connection interface for database portability

Contributing

We welcome contributions! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

版本与发布记录

@drizzle-adapter/d1 共发布 19 个版本,首次发布于 2024/12/03;过去 12 个月发布了 3 个版本。

版本发布日期距今
2.0.1latest2026/11/076 天前
2.0.02026/10/1925 天前
1.1.12026/03/267 个月前
1.0.182025/08/181.2 年前
1.0.172025/07/171.3 年前
1.0.152025/07/121.3 年前

关于 @drizzle-adapter/d1 的常见问题

@drizzle-adapter/d1 是什么?

Cloudflare D1 adapter implementation for the Drizzle Adapter ecosystem.

如何安装 @drizzle-adapter/d1?

在项目目录运行 npm install @drizzle-adapter/d1,或使用 pnpm add / yarn add / bun add。

@drizzle-adapter/d1 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@drizzle-adapter/d1 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@drizzle-adapter/d1 可以商用吗?

@drizzle-adapter/d1 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@drizzle-adapter/d1 的下载量有多少?

根据 npm 官方下载统计,@drizzle-adapter/d1 在 2026/10/13 – 2026/11/11 这 30 天内被下载 20,718 次,日均约 691 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@drizzle-adapter/d1 还在维护吗?

最新版本 2.0.1 发布于 2026/11/07(6 天前);至今共发布 19 个版本,其中过去 12 个月发布了 3 个;首次发布于 2024/12/03。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。