drizzle-orm-d1
БесплатноЗапускает вложенные скриптыНе проверен| Type-safe ORM for Cloudflare D1 databases using Drizzle. Use when: building D1 database schemas, writing type-safe SQL queries, managing migrations with…
Об этом скилле
Drizzle ORM for Cloudflare D1
Status: Production Ready ✅ Last Updated: 2025-12-14 Latest Version: [email protected], [email protected] Dependencies: cloudflare-d1, cloudflare-worker-base
Quick Start (10 Minutes)
1. Install Drizzle
bun add drizzle-orm drizzle-kit
2. Configure Drizzle Kit
Create drizzle.config.ts:
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
schema: './src/db/schema.ts',
out: './migrations',
dialect: 'sqlite', // MANDATORY since drizzle-kit 0.21 (D1 = sqlite)
driver: 'd1-http', // D1 HTTP driver for remote migrations/Studio
dbCredentials: { // MANDATORY: drizzle-kit 0.30+ tightened zod validation
accountId: process.env.CLOUDFLARE_ACCOUNT_ID!,
databaseId: process.env.CLOUDFLARE_DATABASE_ID!,
token: process.env.CLOUDFLARE_D1_TOKEN!,
},
});
drizzle-kit 0.30/0.31 note:
dialectanddbCredentialsare now strictly validated. A config that omitsdialector uses the oldconnectionString/urikeys will fail validation. For D1 usedialect: 'sqlite'+driver: 'd1-http'withaccountId/databaseId/token(or wrangler-based credentials). The runtimemigrate()signature indrizzle-orm/<driver>/migratoris unchanged from 0.36 → 0.45 (it changes only in 1.0-beta, which is out of scope for^0.45).
3. Define 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' }),
});
export const usersRelations = relations(users, ({ many }) => ({
posts: many(posts),
}));
4. Generate & Apply Migrations
bunx drizzle-kit generate # Generate SQL
bunx wrangler d1 migrations apply my-database --local # Apply local
bunx wrangler d1 migrations apply my-database --remote # Apply prod
5. Query in Worker
import { drizzle } from 'drizzle-orm/d1';
import { users } from './db/schema';
import { eq } from 'drizzle-orm';
export default {
async fetch(request: Request, env: { DB: D1Database }): Promise<Response> {
const db = drizzle(env.DB);
const allUsers = await db.select().from(users).all();
return Response.json(allUsers);
},
};
Critical Rules
Always Do
| Rule | Why |
|---|---|
Use drizzle-kit generate for migrations |
Never write SQL manually |
| Test migrations locally first | --local before --remote |
Use .get() for single results |
Returns first row or undefined |
Use db.batch() for transactions |
D1 doesn't support SQL BEGIN/COMMIT |
Use integer with mode: 'timestamp' for dates |
D1 has no native date type |
Use .$defaultFn() for dynamic defaults |
Not .default() for functions |
Never Do
| Rule | Why |
|---|---|
Use SQL BEGIN TRANSACTION |
D1 requires batch API (Error #1) |
Mix drizzle-kit migrate and wrangler apply |
Use Wrangler only |
Use drizzle-kit push for production |
Use generate + apply |
| Commit credentials in drizzle.config.ts | Use env vars |
Use .default() for function calls |
Use .$defaultFn() instead |
Top 5 Critical Errors
| # | Error | Solution |
|---|---|---|
| 1 | D1_ERROR: Cannot use BEGIN TRANSACTION |
Use db.batch([...]) instead of db.transaction() |
| 2 | FOREIGN KEY constraint failed |
Define cascading: .references(() => users.id, { onDelete: 'cascade' }) |
| 3 | env.DB is undefined |
Ensure binding in wrangler.jsonc matches env.DB |
| 4 | No such module "wrangler" |
Use import { drizzle } from 'drizzle-orm/d1' |
| 5 | Type instantiation excessively deep |
Use InferSelectModel<typeof users> for explicit types |
See: references/error-catalog.md for all 12 errors with complete solutions.
Common Patterns Summary
| Pattern | Use Case | Template |
|---|---|---|
| CRUD Operations | Basic database operations | templates/basic-queries.ts |
| Relations & Joins | Nested queries, manual joins | templates/relations-queries.ts |
| Batch Operations | Transactions (D1 batch API) | templates/transactions.ts |
| Schema Design | Naming, indexes, soft deletes | references/schema-patterns.md |
Configuration Summary
| File | Purpose | Template |
|---|---|---|
drizzle.config.ts |
Driz |
Установить drizzle-orm-d1 в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл drizzle-orm-d1?
| Type-safe ORM for Cloudflare D1 databases using Drizzle. Use when: building D1 database schemas, writing type-safe SQL queries, managing migrations with Drizzle Kit, defining table relations, implementing prepared statements, using D1 batch API, or encountering D1_ERROR, transaction errors, foreign key constraint failures, or schema inference issues.
Как установить скилл drizzle-orm-d1?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл drizzle-orm-d1 запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
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