drizzle-orm-d1
БесплатноБез исполняемых скриптовНе проверенType-safe Drizzle ORM patterns for Cloudflare D1 databases: schema definition, migration management with Drizzle Kit and drizzle.config.ts, relations and…
Об этом скилле
Drizzle ORM for Cloudflare D1
Status: Production Ready ✅ Last Updated: 2025-10-24 Latest Version: [email protected], [email protected] Dependencies: cloudflare-d1, cloudflare-worker-base
Quick Start (10 Minutes)
1. Install Drizzle
npm install drizzle-orm
npm install -D drizzle-kit
# Or with pnpm
pnpm add drizzle-orm
pnpm add -D drizzle-kit
Why Drizzle?
- Type-safe queries with full TypeScript inference
- SQL-like syntax (no magic, no abstraction overhead)
- Serverless-ready (works perfectly with D1)
- Zero dependencies (except database driver)
- Excellent DX with IDE autocomplete
- Migrations that work with Wrangler
2. Configure Drizzle Kit
Create drizzle.config.ts in your project root:
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
schema: './src/db/schema.ts',
out: './migrations',
dialect: 'sqlite',
driver: 'd1-http',
dbCredentials: {
accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
databaseId: process.env.CLOUDFLARE_DATABASE_ID!,
token: process.env.CLOUDFLARE_D1_TOKEN!,
},
});
CRITICAL:
dialect: 'sqlite'- D1 is SQLite-baseddriver: 'd1-http'- For remote database access via HTTP API- Use environment variables for credentials (never commit these!)
3. Configure Wrangler
Update wrangler.jsonc:
{
"name": "my-worker",
"main": "src/index.ts",
"compatibility_date": "2025-10-11",
"d1_databases": [
{
"binding": "DB",
"database_name": "my-database",
"database_id": "your-database-id",
"preview_database_id": "local-db",
"migrations_dir": "./migrations" // ← Points to Drizzle migrations!
}
]
}
Why this matters:
migrations_dirtells Wrangler where to find SQL migration files- Drizzle generates migrations in
./migrations(from drizzle.config.tsout) - Wrangler can apply Drizzle-generated migrations with
wrangler d1 migrations apply
4. Define Your Schema
Create src/db/schema.ts:
import { sqliteTable, text, integer } from 'drizzle-orm/sqlite-core';
import { relations } from 'drizzle-orm';
export const users = sqliteTable('users', {
id: integer('id').primaryKey({ autoIncrement: true }),
email: text('email').notNull().unique(),
name: text('name').notNull(),
createdAt: integer('created_at', { mode: 'timestamp' }).$defaultFn(() => new Date()),
});
export const posts = sqliteTable('posts', {
id: integer('id').primaryKey({ autoIncrement: true }),
title: text('title').notNull(),
content: text('content').notNull(),
authorId: integer('author_id')
.notNull()
.references(() => users.id, { onDelete: 'cascade' }),
createdAt: integer('created_at', { mode: 'timestamp' }).$defaultFn(() => new Date()),
});
// Define relations for type-safe joins
export const usersRelations = relations(users, ({ many }) => ({
posts: many(posts),
}));
export const postsRelations = relations(posts, ({ one }) => ({
author: one(users, { fields: [posts.authorId], references: [users.id] }),
}));
Key Points:
- Use
integerfor auto-incrementing IDs - Use
integerwithmode: 'timestamp'for dates (D1 doesn't have native date type) - Use
.$defaultFn()for dynamic defaults (not.default()for functions) - Define relations separately for type-safe joins
5. Generate & Apply Migrations
# Step 1: Generate SQL migration from schema
npx drizzle-kit generate
# Step 2: Apply to local database (for testing)
npx wrangler d1 migrations apply my-database --local
# Step 3: Apply to production database
npx wrangler d1 migrations apply my-database --remote
Why this workflow:
drizzle-kit generatecreates versioned SQL files in./migrations- Test locally first with
--localflag - Apply to production only after local testing succeeds
- Wrangler reads the migrations and applies them to D1
6. Query in Your Worker
Create src/index.ts:
import { drizzle } from 'drizzle-orm/d1';
import { users, posts } from './db/schema';
import { eq } from 'drizzle-orm';
export interface Env {
DB: D1Database;
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const db = drizzle(env.DB);
// Type-safe select with full inference
const allUsers = await db.select().from(users);
// Select with where clause
const user = await db
.select()
.from(users)
.where(eq(users.email, '[email protected]'))
.get(); // .get() returns first result or undefined
// Insert with returning
const [newUser] = await db
.insert(users)
.values({ email: '[email protected]', name: 'New User' })
.returning();
// Update
await db
.update(users)
.set({ name: 'Updated Name' })
.where(eq(users.id, 1));
// Delete
await db
.delete(users)
.where(eq(users.id, 1));
return Response.json({ allUsers, user, newUser });
},
};
**CRITI
Установить drizzle-orm-d1 в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл drizzle-orm-d1?
Type-safe Drizzle ORM patterns for Cloudflare D1 databases: schema definition, migration management with Drizzle Kit and drizzle.config.ts, relations and relational queries, joins, prepared statements, the D1 batch API for transaction-like work, and Workers/Wrangler integration. Documents 12 known pitfalls including D1 transaction errors (SQL BEGIN is unsupported), foreign key constraint failures during migrations, module import errors under Wrangler, missing D1 bindings, migration apply failures, schema TypeScript inference errors, prepared statement caching, rollback patterns, TypeScript strict mode errors, remote versus local database confusion, and mixing wrangler.toml with wrangler.jsonc. Use when building a D1 schema, writing type-safe queries, running or repairing Drizzle migrations, or hitting D1_ERROR, BEGIN TRANSACTION, d1 binding, or schema inference errors.
Как установить скилл drizzle-orm-d1?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл drizzle-orm-d1 запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
doc-coauthoring
Guide users through a structured workflow for co-authoring documentation. Use when user wants to write documentation, proposals, technical specs, decision…
от Anthropicacademy-guide
Stop and check this skill before finishing any reply to a question about how to use Claude or a Claude product — it recommends matching courses, tutorials…
от Anthropicinternal-comms
A set of resources to help me write all kinds of internal communications, using the formats that my company likes to use. Claude should use this skill…
от Anthropicskill-development
This skill should be used when the user wants to "create a skill", "add a skill to plugin", "write a new skill", "improve skill description", "organize skill…
от Anthropic