مهارةEnglish

Cloudflare D1 with wrangler: migrations, execute, export and FTS5 notes

Create and manage Cloudflare D1 databases from the CLI with wrangler 4: schema migrations, running SQL locally or remotely, exports, Time Travel restore, and the FTS5 caveats.

تنزيل SKILL.md الملف الخام (Markdown)

التثبيت في Claude Code

ضع الملف في مجلد باسم المهارة داخل مجلد skills الخاص بـ Claude Code، ثم ابدأ جلسة جديدة. الأمر التالي يفعل ذلك:

bash
mkdir -p ~/.claude/skills/wrangler-d1 && \
  curl -fsSL https://md2.dev/library/raw/wrangler-d1.md \
  -o ~/.claude/skills/wrangler-d1/SKILL.md

المعاينة

Cloudflare D1 with wrangler

When to use

Any task that creates, migrates, seeds, queries, backs up or restores a D1 database. For deployment of the Worker that uses it see wrangler-deploy; for FTS5 query design see sqlite-fts.

Prerequisites

BASH
npx wrangler --version     # 4.x
npx wrangler whoami        # logged in? otherwise: npx wrangler login

Workflow

  1. Create the database and copy the printed binding block into wrangler.jsonc.
  2. Put every schema change in a migration file; never edit applied ones.
  3. Apply to local first (default), then to remote.
  4. Verify with a SELECT and a row count.
  5. Deploy the Worker only after the remote migration succeeded.
BASH
npx wrangler d1 create my-db
# wrangler.jsonc:
# "d1_databases": [{ "binding": "DB", "database_name": "my-db",
#                    "database_id": "<uuid>", "migrations_dir": "migrations" }]

npx wrangler d1 migrations create my-db add_documents    # migrations/0001_add_documents.sql
npx wrangler d1 migrations list my-db --remote           # what is still unapplied
npx wrangler d1 migrations apply my-db                   # local
npx wrangler d1 migrations apply my-db --remote          # production

Running SQL

d1 execute runs against the local database unless you pass --remote.

BASH
npx wrangler d1 execute my-db --remote --command "SELECT count(*) AS n FROM documents"
npx wrangler d1 execute my-db --remote --file seed.sql
npx wrangler d1 execute my-db --remote --json --command "SELECT id, title FROM documents LIMIT 5" \
  | jq '.[0].results'
npx wrangler d1 execute my-db --local --command "PRAGMA table_list"

Backup, export and restore

BASH
npx wrangler d1 export my-db --remote --output backup.sql
npx wrangler d1 export my-db --remote --no-data --output schema.sql
npx wrangler d1 export my-db --remote --table documents --output documents.sql

npx wrangler d1 time-travel info my-db                       # current bookmark
npx wrangler d1 time-travel restore my-db --timestamp 2026-10-10T08:00:00Z

Time Travel covers the last 30 days. Restoring overwrites the database in place, so export first if unsure.

Migration rules

  • One concern per file, prefix NNNN_, plain SQL, idempotent where cheap (CREATE TABLE IF NOT EXISTS).
  • SQLite ALTER TABLE cannot drop a column that is indexed or referenced; create a new table, copy, drop, rename.
  • Foreign keys are enforced; use PRAGMA defer_foreign_keys = on inside a migration that reorders tables.
  • Keep a single statement under 100 KB and a query under 100 bound parameters; split big inserts into batches.

FTS5 notes

D1 supports FTS5 virtual tables, with two catches:

SQL
CREATE VIRTUAL TABLE docs_fts USING fts5(title, body, content='documents', content_rowid='rowid',
                                         tokenize='unicode61 remove_diacritics 2');
  • d1 export fails on databases that contain virtual tables. Drop the FTS tables (and recreate them from the content table after import) or take a Time Travel bookmark instead.
  • An external-content FTS table needs triggers on the base table to stay in sync, and INSERT INTO docs_fts(docs_fts) VALUES('rebuild') after bulk loads.

Gotchas

  • Forgetting --remote silently edits the local copy; always read the "Resource location" line in the output.
  • wrangler d1 execute --file with a huge dump may time out: split it into chunks of a few thousand rows.
  • A failed migration leaves earlier ones applied; fix forward with a new numbered file.
  • Do not store secrets or large blobs in D1; use secrets and R2.

Verify

BASH
npx wrangler d1 execute my-db --remote --command "SELECT name FROM sqlite_schema WHERE type IN ('table','index') ORDER BY 1"
npx wrangler d1 migrations list my-db --remote      # expect: No migrations to apply

العودة إلى المهارات