d1-drizzle-schema
jezweb/claude-skills
Generate Drizzle ORM schemas for Cloudflare D1 with correct D1-specific patterns and migrations.
What is d1-drizzle-schema?
Produces Drizzle schema files, migrations, type exports, and documentation for Cloudflare D1 databases. D1 is SQLite-based but enforces foreign keys, lacks native BOOLEAN/DATETIME types, limits bound parameters to 100, and stores JSON as TEXT. Use this skill when creating a new D1 database, adding tables, or scaffolding a data layer.
- Generate D1-correct Drizzle ORM schema files with proper column patterns (text PKs, integer booleans/timestamps, JSON as TEXT)
- Create migration files and npm scripts for local and remote D1 deployment
- Export TypeScript types (User, NewUser) from schema definitions
- Generate DATABASE_SCHEMA.md documentation of tables, relationships, indexes, and constraints
- Handle D1 quirks: enforced foreign keys, 100 bound parameter limit, single-threaded concurrency
How to install d1-drizzle-schema
npx skills add https://github.com/jezweb/claude-skills --skill d1-drizzle-schema- Node.js and npm installed
- Cloudflare Workers project set up
- wrangler CLI configured with D1 database binding
How to use d1-drizzle-schema
- 1.Describe your data model: tables, columns, relationships, and indexing needs
- 2.Generate Drizzle schema files using D1-correct patterns (text PKs, integer booleans/timestamps, JSON as TEXT)
- 3.Add Drizzle relations for query builder helpers separate from FK constraints
- 4.Export TypeScript types from the schema
- 5.Copy drizzle-config-template.ts to drizzle.config.ts and update schema path
- 6.Add migration scripts to package.json (db:generate, db:migrate:local, db:migrate:remote)
- 7.Run migrations on both local and remote environments before testing
- 8.Generate DATABASE_SCHEMA.md to document tables, relationships, indexes, and constraints
Use cases
- Scaffold a new Cloudflare Workers project with D1 database and Drizzle ORM
- Add new tables to an existing D1 schema while respecting D1 constraints
- Implement bulk insert operations with correct batching for the 100 parameter limit
- Document database schema for team reference and future migrations
- Convert existing SQLite schemas to D1-compatible Drizzle patterns
- Cloudflare Workers developers
- Full-stack developers using D1 as their database
- Teams building serverless applications on Cloudflare
- Developers migrating from standard SQLite to D1
d1-drizzle-schema FAQ
D1 is SQLite-based but lacks native BOOLEAN and DATETIME types. Use integer({ mode: 'boolean' }) for booleans (stored as 0/1) and integer({ mode: 'timestamp' }) for timestamps (stored as unix seconds). This prevents subtle bugs when querying or comparing values.
D1 limits bound parameters per query to 100, affecting bulk inserts. Calculate batch size as Math.floor(100 / COLUMNS_PER_ROW) and insert in batches. For example, a 5-column table can insert 20 rows per query.
No. D1 always enforces foreign keys and you cannot disable them. Design your schema with this in mind and use onDelete/onUpdate cascade or restrict as needed.
D1 stores JSON as TEXT but provides json_extract, ->, and ->> operators for querying. Use text('column', { mode: 'json' }).$type<YourType>() in Drizzle to auto-serialize/deserialize.
Yes. Always run wrangler d1 migrations apply DB --local and wrangler d1 migrations apply DB --remote before testing to ensure both environments are in sync.
Full instructions (SKILL.md)
Source of truth, from jezweb/claude-skills.
name: d1-drizzle-schema description: "Generate Drizzle ORM schemas for Cloudflare D1 databases with correct D1-specific patterns. Produces schema files, migration commands, type exports, and DATABASE_SCHEMA.md documentation. Handles D1 quirks: foreign keys always enforced, no native BOOLEAN/DATETIME types, 100 bound parameter limit, JSON stored as TEXT. Use when creating a new database, adding tables, or scaffolding a D1 data layer." compatibility: claude-code-only
D1 Drizzle Schema
Generate correct Drizzle ORM schemas for Cloudflare D1. D1 is SQLite-based but has important differences that cause subtle bugs if you use standard SQLite patterns. This skill produces schemas that work correctly with D1's constraints.
Critical D1 Differences
| Feature | Standard SQLite | D1 |
|---|---|---|
| Foreign keys | OFF by default | Always ON (cannot disable) |
| Boolean type | No | No — use integer({ mode: 'boolean' }) |
| Datetime type | No | No — use integer({ mode: 'timestamp' }) |
| Max bound params | ~999 | 100 (affects bulk inserts) |
| JSON support | Extension | Always available (json_extract, ->, ->>) |
| Concurrency | Multi-writer | Single-threaded (one query at a time) |
Workflow
Step 1: Describe the Data Model
Gather requirements: what tables, what relationships, what needs indexing. If working from an existing description, infer the schema directly.
Step 2: Generate Drizzle Schema
Create schema files using D1-correct column patterns:
import { sqliteTable, text, integer, real, index, uniqueIndex } from 'drizzle-orm/sqlite-core'
export const users = sqliteTable('users', {
// UUID primary key (preferred for D1)
id: text('id').primaryKey().$defaultFn(() => crypto.randomUUID()),
// Text fields
name: text('name').notNull(),
email: text('email').notNull(),
// Enum (stored as TEXT, validated at schema level)
role: text('role', { enum: ['admin', 'editor', 'viewer'] }).notNull().default('viewer'),
// Boolean (D1 has no BOOL — stored as INTEGER 0/1)
emailVerified: integer('email_verified', { mode: 'boolean' }).notNull().default(false),
// Timestamp (D1 has no DATETIME — stored as unix seconds)
createdAt: integer('created_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),
updatedAt: integer('updated_at', { mode: 'timestamp' }).notNull().$defaultFn(() => new Date()),
// Typed JSON (stored as TEXT, Drizzle auto-serialises)
preferences: text('preferences', { mode: 'json' }).$type<UserPreferences>(),
// Foreign key (always enforced in D1)
organisationId: text('organisation_id').references(() => organisations.id, { onDelete: 'cascade' }),
}, (table) => ({
emailIdx: uniqueIndex('users_email_idx').on(table.email),
orgIdx: index('users_org_idx').on(table.organisationId),
}))
See references/column-patterns.md for the full type reference.
Step 3: Add Relations
Drizzle relations are query builder helpers (separate from FK constraints):
import { relations } from 'drizzle-orm'
export const usersRelations = relations(users, ({ one, many }) => ({
organisation: one(organisations, {
fields: [users.organisationId],
references: [organisations.id],
}),
posts: many(posts),
}))
Step 4: Export Types
export type User = typeof users.$inferSelect
export type NewUser = typeof users.$inferInsert
Step 5: Set Up Drizzle Config
Copy assets/drizzle-config-template.ts to drizzle.config.ts and update the schema path.
Step 6: Add Migration Scripts
Add to package.json:
{
"db:generate": "drizzle-kit generate",
"db:migrate:local": "wrangler d1 migrations apply DB --local",
"db:migrate:remote": "wrangler d1 migrations apply DB --remote"
}
Always run on BOTH local AND remote before testing.
Step 7: Generate DATABASE_SCHEMA.md
Document the schema for future sessions:
- Tables with columns, types, and constraints
- Relationships and foreign keys
- Indexes and their purpose
- Migration workflow
Bulk Insert Pattern
D1 limits bound parameters to 100. Calculate batch size:
const BATCH_SIZE = Math.floor(100 / COLUMNS_PER_ROW)
for (let i = 0; i < rows.length; i += BATCH_SIZE) {
await db.insert(table).values(rows.slice(i, i + BATCH_SIZE))
}
D1 Runtime Usage
import { drizzle } from 'drizzle-orm/d1'
import * as schema from './schema'
// In Worker fetch handler:
const db = drizzle(env.DB, { schema })
// Query patterns
const all = await db.select().from(schema.users).all() // Array<User>
const one = await db.select().from(schema.users).where(eq(schema.users.id, id)).get() // User | undefined
const count = await db.select({ count: sql`count(*)` }).from(schema.users).get()
Reference Files
| When | Read |
|---|---|
| D1 vs SQLite, JSON queries, limits | references/d1-specifics.md |
| Column type patterns for Drizzle + D1 | references/column-patterns.md |
Assets
| File | Purpose |
|---|---|
| assets/drizzle-config-template.ts | Starter drizzle.config.ts for D1 |
| assets/schema-template.ts | Example schema with all common D1 patterns |
Related skills
More from jezweb/claude-skills and the wider catalog.

d1-migration
Cloudflare D1 migration workflow: generate with Drizzle, inspect SQL for gotchas, apply to local and remote, fix stuck migrations, handle partial failures. Use when running migrations, fixing migration errors, or setting up D1 schemas.

db-seed
Generate database seed scripts with realistic sample data. Reads Drizzle schemas or SQL migrations, respects foreign key ordering, produces idempotent TypeScript or SQL seed files. Handles D1 batch limits, unique constraints, and domain-appropriate data. Use when populating dev/demo/test databases. Triggers: 'seed database', 'seed data', 'sample data', 'populate database', 'db seed', 'test data', 'demo data', 'generate fixtures'.

deep-research
Deep research and discovery before building something new. Explores local projects for reusable code, researches competitors, reads forums and reviews, analyses plugin ecosystems, investigates technical options, and produces a comprehensive research brief. Three depths: focused (30 min), wide (1-2 hours), deep (3-6 hours). Triggers: 'research this', 'discovery', 'explore the space', 'what should I build', 'competitive analysis', 'before I start building', 'research before coding'. Not for cited fact-checking research reports (a separate harness does those); this is pre-build product discovery.

design-loop
Autonomous multi-page site builder using a baton-passing loop. Each iteration reads a task from .design/next-prompt.md, generates a page in HTML/Tailwind, integrates it into the site, verifies visually, then writes the next task to keep the loop alive. Use whenever the user asks to build an entire site autonomously, build all pages of a site, generate multiple pages in sequence, or run a 'design loop' / 'baton loop' / 'autonomous site build' — even if they say 'just keep going' or 'build the next page' or 'next page' mid-flow.

design-review
Review a web app or page for visual design quality — layout, typography, spacing, colour, hierarchy, consistency, interaction patterns, and responsive behaviour. Not a UX audit (that checks usability) — this checks whether it looks professional and polished. Produces a design findings report with screenshots. Triggers: 'design review', 'does this look good', 'review the design', 'check the layout', 'is this polished', 'visual review', 'design audit', 'make it look better', 'it looks off'.

design-system
Extract a complete design system from an existing website or screenshot into a DESIGN.md file. Analyses colours, typography, component styles, spacing, and atmosphere through browser automation and HTML inspection. Produces a semantic design system document optimised for consistent page generation. Triggers: 'extract design system', 'design system', 'create DESIGN.md', 'analyse the design', 'what design does this site use', 'extract styles from', 'reverse engineer the design'.