@drizzle-adapter/d1
v1.0.6
Published
Cloudflare D1 adapter implementation for the Drizzle Adapter ecosystem.
Downloads
370
Readme
@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:
- Edge Applications: Data served from the closest location
- Cloudflare Workers: Native database for Workers applications
- Global Applications: Automatic global distribution
- Cost-Sensitive Projects: Included in Workers pricing
- 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';
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
- Edge Optimization: Queries are automatically optimized for edge execution
- JSON Handling: Store JSON data as TEXT and parse/stringify as needed
- Error Handling: Implement proper error handling for edge environments
- Query Optimization: Minimize the number of queries per request
- 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.
Related Packages
- @drizzle-adapter/core - Core interfaces and types
- @drizzle-adapter/sqlite-core - Shared SQLite functionality