Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Cloudflare D1 Knowledge Patch?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/nevaberry-cloudflare-d1-knowledge-patch-nevaberry-plugins)
---
name: cloudflare-d1-knowledge-patch
description: Cloudflare D1
version: null
license: MIT
metadata:
author: Nevaberry
---
# Cloudflare D1
Load this skill when configuring D1, writing Worker queries, applying migrations,
working with replication and data location, or handling recovery and diagnostics.
Use the topic references for complete guidance and examples.
## Reference index
| Reference | Topics |
| --- | --- |
| [Backup, recovery, and transfer](references/backup-and-transfer.md) | Time Travel, undelete, alpha backups, SQL imports, export compatibility, retention |
| [Migrations and local development](references/migrations-and-local-development.md) | Target selection, nested migrations, migration tracking, Pages, persistence, tests, remote bindings |
| [Operations and debugging](references/operations-and-debugging.md) | Permissions, quotas, result limits, error diagnostics, retries, metrics, Insights |
| [Query API and SQL](references/query-api-and-sql.md) | Bindings, result shapes, batch execution, SQL, PRAGMAs, AI Search beta |
| [Replication and data location](references/replication-and-location.md) | Placement, jurisdictions, replication controls, Sessions API, bookmarks, routing metadata |
## Compatibility changes and limits
### Explicitly select the database target
Starting in Wrangler 3.33.0, `wrangler d1 execute` and
`wrangler d1 migrations apply` target the local database by default.
Use `--remote` for the deployed database or `--local` to select local explicitly.
```sh
wrangler d1 migrations apply example-db --remote
```
In `wrangler dev`, a D1 binding with `"remote": true` uses the deployed database;
writes through that binding update it. Pages local development supports local
D1 databases only.
### Write access
Dashboard Tables-tab writes require a role with write access. HTTP API writes,
including `/query`, require `D1:Edit`, even for tokens that previously worked
with `D1:Read` and another product's `Edit` permission.
### Retired alpha backups
As of July 1, 2025, Wrangler v3's `wrangler d1 backup` can no longer create or
access alpha backups. Previously saved alpha backups can still migrate to a new
generally available D1 database.
### Export constraints and compatibility
A running `wrangler d1 export` blocks other database requests.
To include virtual tables such as FTS5 and R*Tree, pass
`--compatibility=sqlite3_cli_only`. For the export API, set
`dump_options.compatibility` to `sqlite3_cli_only` in the POST body.
### Result size and account limits
Starting November 4, 2026, D1 rejects query results larger than 50 MB;
REST API imports and exports are exempt. Select only needed columns and paginate
large results with `LIMIT` and `OFFSET`.
Workers Free daily-limit enforcement began February 10, 2025. When an account
exceeds its daily D1 limits, queries through both the Workers binding and REST API
fail until the next reset at 00:00 UTC. D1 emails when either daily row limit is
reached. The combined Workers Paid account storage limit increased to 1 TB.
## Recovery and transfer
Time Travel is always on for databases reporting `version: production` in
`wrangler d1 info <database>`. Its CLI commands require Wrangler 3.4.0 or later.
Retention is 7 days on Workers Free and 30 days on Workers Paid, with restoration
to any minute in that window. History and restore operations have no extra charge.
A restore overwrites the database in place and cancels in-flight queries and
transactions. It returns a bookmark for the immediately preceding state, which
can undo the restore. Time Travel bookmarks recover only their source database.
```sh
wrangler d1 time-travel restore example-db --timestamp="$RESTORE_TIMESTAMP"
wrangler d1 time-travel restore example-db --bookmark="$PRE_RESTORE_BOOKMARK"
```
The undelete API accepts requests within seven days of deletion and returns an
error for older deletions.
Before importing a SQLite dump, remove `BEGIN TRANSACTION`, `COMMIT`, and any
`CREATE TABLE _cf_KV` statement. Split imports larger than 5 GiB into multiple
SQL files. For `Statement too long`, split a large multi-row `INSERT` into smaller
statements. Create referenced tables before loading rows that depend on them.
Use Workflows to export D1 through the REST API into R2 for retention beyond the
Time Travel window.
## Migrations and local configuration
Set `migrations_pattern` on the D1 binding to discover nested migration files.
The glob is relative to the Wrangler config file and defaults to
`${migrations_dir}/*.sql`. An explicit pattern requires an explicit
`migrations_dir` and must start with that directory.
Use `migrations/*/migration.sql` for layouts such as
`migrations/0001_init/migration.sql`, or `migrations/**/*.sql` for any depth.
The migrations table records paths relative to `migrations_dir`.
`wrangler d1 migrations create` writes at the top level of `migrations_dir`.
For a pattern matching only nested files, use an ORM generator such as
`drizzle-kit generate`. Applied migrations use `d1_migrations` by default;
configure `migrations_table` to change the table name.
For Pages local development, set `preview_database_id` to the binding name and
keep `database_id` set to the database UUID. For `unstable_dev()` tests, use a
user-defined `preview_database_id` and apply migrations with `--local` before
starting the test server. Wrangler v3 and later persist local D1 data by default;
Wrangler v2 requires `--persist`.
## Query bindings and results
D1 accepts only anonymous `?` and numbered `?NNN` placeholders. Supply numbered
placeholder values to `bind()` in parameter-number order.
`run()` and `all()` are aliases returning a `D1Result` with rows in `results` and
execution metadata in `meta`. `results` is `[]` for an empty row set and `null`
when row results do not apply. `first(columnName)` returns `null` for no rows;
column existence is checked only when there is a row to read.
`batch()` returns one result per prepared statement in input order, each with
its own rows and metadata. Python Workers convert a statement's row array with
`.to_py()`. `exec()` takes newline-separated statements without parameter
bindings, returns `{ count, duration }` with duration in milliseconds, and stops
before remaining statements if one fails.
Bound booleans are stored as SQLite `INTEGER` values and returned as JavaScript
numbers (`0` or `1`). Bind an `ArrayBuffer` or view such as `Uint8Array` for a
`BLOB`; D1 reads it back as a JavaScript array. The Workers binding rejects
`BigInt` parameters, and large SQLite `int64` results may lose precision because
numeric results use JavaScript numbers.
## Replication, sessions, and location
Enable Read Replication in database Settings, or use the database endpoint with
`PUT`, a `D1:Edit` token, and `read_replication.mode` set to `auto` or `disabled`.
D1 provisions one replica per supported region, including the primary's region.
Replicas activate based on traffic, cost no extra, and stay within a database's
jurisdiction. Eligible reads through the Workers Sessions API route automatically.
The Sessions API is available only through the D1 Workers binding. Queries
outside a session go to the primary. `withSession("first-primary")` starts on
the primary and allows subsequent reads on replicas. The default,
`"first-unconstrained"`, allows the first read on any instance. Both provide
sequential consistency.
`session.getBookmark()` returns the latest bookmark, or `null` before the first
query in a session started without a bookmark. Pass a saved bookmark directly to
`withSession()` to start at a database version at least as recent as that bookmark.
Existing session code works with replication disabled; replicas can take up to
24 hours to stop serving requests after disablement.
Remote results expose `meta.served_by_region` and `meta.served_by_primary`
regardless of session use or replication settings. Both are `undefined` locally
in `wrangler dev`.
By default, D1 places the primary near the origin of the creation request.
At creation, `--location` prefers a region; a jurisdiction guarantees where the
database runs and stores data and takes precedence over a location hint.
Jurisdictions include `eu`, `fedramp`, and `us`. An existing database cannot gain
or change a jurisdiction; Workers can access it from anywhere.
## Diagnostics and performance
Log `error.message` for binding diagnostics; before Wrangler 3.1.1, read
`error?.cause?.message`. The HTTP query API returns `400 Bad Request` for invalid
SQL and `429 Too Many Requests` for database overload.
D1 makes up to two retries on retryable errors for queries it classifies as
read-only: `SELECT`, `EXPLAIN`, and read-only `WITH`. Read
`D1Result.meta.total_attempts` for the total, including the initial attempt.
If an automatic retry makes a write, D1 rolls back that attempt.
Retry documented transient errors at the application level only when the
operation is idempotent; the operations reference lists the exact messages.
Run `PRAGMA optimize` after a schema change such as adding an index.
`PRAGMA optimize(-1)` is unavailable. `PRAGMA defer_foreign_keys = ON` still
allows `ON DELETE CASCADE` actions to execute. D1 accepts `LIMIT` on `UPDATE`
and `DELETE` to cap rows changed by one statement.
Read `meta.timings.sql_duration_ms` for database-instance execution time,
excluding network time. D1 Insights index recommendations include a
`CREATE INDEX` statement, the queries it is expected to speed up, and usage
metrics. Enable or disable recommendations through the dashboard, `cf` CLI,
or API.
## AI Search integration (beta)
AI Search runs a read-only SQL query against D1 and indexes each returned row as
a document. Scheduled syncs update the index as rows are added, changed, or
removed. The query reference includes the instance-creation request example.