samuelpatro/.claude / skills/drizzle-orm-d1
drizzle-orm-d1
VerifiedType-safe ORM for Cloudflare D1 using Drizzle. Use when building D1 schemas, writing type-safe queries, generating migrations with Drizzle Kit, defining relations, using db.batch, or hitting D1_ERROR, BEGIN TRANSACTION failures, foreign key constraints, env.DB undefined, or schema inference issues.
| File | Kind | Size |
|---|---|---|
| ERRORS.md | markdown | 10.1 KB |
| MIGRATIONS.md | markdown | 6.4 KB |
| QUERIES.md | markdown | 9.3 KB |
| SCHEMA-PATTERNS.md | markdown | 7.9 KB |
| SKILL.md | skill md | 12.2 KB |
ERRORS.md
View on GitHub# Error Catalog
Every error here has been hit at least once on a real D1 + Drizzle project. Solutions are the actual fix, not a workaround.
## 1. `D1_ERROR: Cannot use BEGIN TRANSACTION inside a transaction`
D1 does not support SQL transaction statements. `db.transaction()` and any raw `BEGIN`/`COMMIT` will throw.
**Fix**: use `db.batch([...])`.
```ts
// wrong
await db.transaction(async (tx) => {
await tx.insert(users).values(u);
await tx.insert(posts).values(p);
});
// right
await db.batch([
db.insert(users).values(u),
db.insert(posts).values(p),
]);
```
## 2. `FOREIGN KEY constraint failed`
A row references a parent that doesn't exist, or you tried to delete a parent with children and didn't declare a cascade.
**Fix**: declare `onDelete` explicitly when the column is defined.
```ts
authorId: integer("author_id")
.notNull()
.references(() => users.id, { onDelete: "cascade" }),
```
If the rows already exist, generate a migration that includes the FK with the desired action; you cannot ALTER constraint-by-constraint in SQLite, drizzle-kit handles the table-rebuild dance.
## 3. `env.DB is undefined`
Worker runtime is fine, the binding is not wired up.
**Fix**: in `wrangler.jsonc`, the `binding` field must equal the property name your code reads.
```jsonc
{
"d1_databases": [
{
"binding": "DB", // env.DB
"database_name": "my-database",
"database_id": "...",
"migrations_dir": "./src/server/db/migrations"
}
]
}
```
Also confirm types: in `worker-configuration.d.ts` (or your `Env` type) `DB` is typed as `D1Database`. If you've never run `wrangler types`, do it once.
## 4. `db.query.X is undefined` or relations missing in result
The relational query API (`db.query.users.findFirst({ with: { posts: true } })`) is silent when the relation isn't reachable. Two failure modes:
- `client.ts` doesn't pass `{ schema }` to `drizzle(d1)`.
- `schema/index.ts` doesn't re-export the `*Relations` object.
**Fix**: both must be true.
```ts
// client.ts
import * as schema from "./schema";
return drizzle(d1, { schema });
// schema/index.ts
export * from "./users"; // exports `users` AND `usersRelations`
export * from "./posts"; // exports `posts` AND `postsRelations`
```
If relations are still missing, check the TS file actually exports `<table>Relations` (typo on the export name is invisible to drizzle).
## 5. `Type instantiation is excessively deep and possibly infinite`
TypeScript hit its inference depth limit, usually inside a join with several relations or a deeply nested `with`.
**Fix**: annotate explicitly so TS doesn't have to infer through the whole graph.
```ts
import type { InferSelectModel } from "drizzle-orm";
type User = InferSelectModel<typeof users>;
async function getUsers(db: DB): Promise<User[]> {
return db.select().from(users).all();
}
```
For relational queries with many `with`, capture the result type once:
```ts
type UserWithPosts = Awaited<ReturnType<typeof loadUserWithPosts>>;
```
## 6. `no such module 'wrangler'` / `Cannot find module 'drizzle-orm/d1'`
Wrong import path for the D1 driver.
**Fix**: import from `drizzle-orm/d1`, not from `wrangler` or `drizzle-orm`.
```ts
// right
import { drizzle } from "drizzle-orm/d1";
// wrong
import { drizzle } from "drizzle-orm";
import { drizzle } from "wrangler";
```
## 7. `wrangler d1 migrations list` shows nothing
Wrangler is looking in the wrong directory.
**Fix**: `migrations_dir` in `wrangler.jsonc` must equal `out` in `drizzle.config.ts`.
```jsonc
"migrations_dir": "./src/server/db/migrations"
```
```ts
out: "./src/server/db/migrations",
```
If they match and the directory contains generated `.sql` files, run `bunx wrangler d1 migrations apply <db> --local` once to initialise the `d1_migrations` table.
## 8. `drizzle-kit generate` produces an empty migration
Either the schema didn't change, or you edited a previously generated migration and re-ran generate against that altered state.
**Fix**: only edit the schema in TypeScript files. Treat generated SQL files as immutable history, except for adding data migrations to the most recent file before commit.
If you genuinely need to start over: delete the unmerged migrations, rerun `generate`. Never delete migrations that have been applied to any environment.
## 9. Rename treated as drop + add (data loss)
`drizzle-kit generate` prompts on rename. If you accept the default or scroll past it, you get `DROP COLUMN` + `ADD COLUMN`, losing every row's value.
**Fix**: read the prompt. Pick the `~ rename` arrow.
```
Is column `username` in `users` table created or renamed from another column?
❯ ~ name › username (rename)
+ username (create column)
```
If you've already shipped the destructive migration to local, restore from a backup or recreate the data, then write a new migration on top. Never edit an applied migration.
## 10. `UNIQUE constraint failed: users.email`
A unique column got a duplicate insert. Common during seed scripts or a re-run of an upsert that wasn't actually idempotent.
**Fix**: use `onConflictDoNothing` or `onConflictDoUpdate`.
```ts
await db
.insert(users)
.values({ email, name })
.onConflictDoUpdate({
target: users.email,
set: { name },
});
```
## 11. `db.batch` type error: tuple expected
Drizzle's `batch` requires a non-empty tuple at the type level. Passing `Array<...>` doesn't type-check.
**Fix**: cast when the length is dynamic.
```ts
const stmts = ids.map((id) =>
db.update(users).set({ active: false }).where(eq(users.id, id)),
);
await db.batch(stmts as [(typeof stmts)[0], ...typeof stmts]);
```
For static lists, write a tuple literal directly and the type works without help.
## 12. `last_insert_rowid()` returns 0 inside a batch
`last_insert_rowid()` is connection-scoped, not statement-scoped. Inside `db.batch`, it works but only references the most recent insert at the moment it executes, which is not always what you expect.
**Fix**: use `.returning()` on the insert and pass the value explicitly.
```ts
const [user] = await db.batch([
db.insert(users).values({ email, name }).returning(),
// not: db.insert(posts).values({ authorId: sql`last_insert_rowid()` })
]);
await db.insert(posts).values({ title, authorId: user[0].id }).run();
```
If you must stay inside a single batch, place the dependent insert immediately after, with a comment explaining the dependency.
## 13. Remote migration ran but production schema unchanged
`wrangler d1 migrations apply DB --remote` was run raw, without `--env production` — it migrated the top-level (dev) config's D1, not the production database under `env.production`.
**Fix**: only migrate remote through the script that bakes in the env selection (`bun run db:migrate:remote`). To see where each side actually stands:
```bash
bunx wrangler d1 migrations list DB --local
bunx wrangler d1 migrations list DB --remote --env production
```
Apply pending migrations in commit order. If a migration was applied to remote but reverted in code, write a follow-up migration that explicitly undoes it. Direct SQL on remote is a last resort and leaves no trail.
## 14. Table-rebuild migration breaks on FK'd tables (rollback or data loss)
SQLite can't express some changes as `ALTER` (dropping a NOT NULL, changing a type or an FK), so drizzle-kit generates a `__new_<table>` rebuild that opens with `PRAGMA foreign_keys=OFF`. D1 runs each migration inside a transaction, where that pragma is a **documented no-op**. Two failure modes, depending on the children's FK actions:
- `restrict`/`no action` children with rows → `DROP TABLE <table>` fails and the whole migration rolls back.
- `onDelete: "cascade"` children → the drop's implicit DELETE cascades and **silently wipes child rows** ([drizzle-orm#4938](https://github.com/drizzle-team/drizzle-orm/issues/4938)).
**`PRAGMA defer_foreign_keys=ON` does NOT save a rebuild**: dropping the parent increments the deferred-violation counter and recreating it never decrements it, so the migration still rolls back at COMMIT.
**Detection**: before applying, read every generated migration. Red flag: a `__new_`-table rebuild or `DROP TABLE` on a table other tables reference.
**Fix — park the references first**, then rebuild, then restore (matrix reference: `0091_tricky_luminals.sql`, which made `ideas.team_id` nullable against four referencing tables):
1. For each child with a **NOT NULL** FK column: `CREATE TABLE __save_<child> AS SELECT * FROM <child>;` then `DELETE FROM <child>;`
2. For each child with a **nullable** FK column: stash `(pk, fk)` into a `__save_*` table, then `UPDATE <child> SET <fk> = NULL;`
3. Run the generated rebuild.
4. Restore from the `__save_*` tables and drop them.
**Verify on a populated local DB** — a rebuild passes happily on an empty database and fails in production.
## 15. `findFirst` inside `db.batch` throws instead of returning `undefined`
`db.query.X.findFirst(...)` as a `db.batch` element throws `TypeError: Cannot read properties of undefined (reading '0')` when no row matches, instead of resolving to `undefined`. ([drizzle-orm#2721](https://github.com/drizzle-team/drizzle-orm/issues/2721))
**Fix**: don't put `findFirst` in a batch. Run it as a separate await, or use the core builder inside the batch — `db.select().from(users).where(...).limit(1)` returns an empty array safely.
## 16. `sql` template query inside `db.batch` throws `Cannot read properties of undefined (reading 'bind')`
Raw `db.all(sql\`...\`)` / `db.run(sql\`...\`)` elements break inside `db.batch`, even though the same statement works standalone. ([drizzle-orm#2277](https://github.com/drizzle-team/drizzle-orm/issues/2277))
**Fix**: inside a batch, use the query builder (`db.insert(...).onConflictDoUpdate(...)` etc.), not `sql` template queries. If raw SQL is unavoidable, run it outside the batch.
## 17. `no such table: <name>` after generate but before apply
You generated the migration but didn't apply it locally yet.
**Fix**:
```bash
bunx wrangler d1 migrations apply my-database --local
```
If you applied it and still see the error, your code is hitting a different D1 instance than the one wrangler points at (e.g. preview vs. dev). Confirm `database_id` in `wrangler.jsonc`.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |