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)
---
name: cloudflare-d1-knowledge-patch
description: Cloudflare D1
version: null
license: MIT
metadata:
author: Nevaberry
---
# Cloudflare D1 Knowledge Patch
Load this skill when working with D1 bindings and SQL, migrations, local
development, recovery, placement, read replication, or operational diagnostics.
Use the topic references for complete configuration and command examples.
## Reference index
| Reference | Topics |
| --- | --- |
| [Backup, Restore, and Transfer](references/backup-restore-and-transfer.md) | Time Travel, undelete, SQL import/export, virtual tables, R2 retention, alpha backups and dumps |
| [Binding and SQL](references/binding-and-sql.md) | Parameters, result shapes, batch and exec, SQL inspection and behavior, AI Search beta |
| [Migrations and Local Development](references/migrations-and-local-development.md) | Local/remote targets, migration paths and tracking, persistence, Pages, tests |
| [Operations and Debugging](references/operations-and-debugging.md) | Write access, errors, retries, resource failures, timing, analytics, index recommendations |
| [Placement, Jurisdictions, and Limits](references/placement-jurisdictions-and-limits.md) | Location hints, jurisdictions, Terraform, account limits, query result size |
| [Read Replication](references/read-replication.md) | Provisioning, controls, session routing, bookmarks, execution location, regional metrics |
## Changed behavior and restrictions
### Local targets and deployed writes
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`, set `"remote": true` on a D1 binding to use the deployed
database from a local Worker. 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.
### Daily limits and result size
Workers Free daily-limit enforcement began on February 10, 2025.
Exceeding daily D1 limits makes Workers-binding and REST API queries fail
until the reset at 00:00 UTC. D1 emails when either daily row limit is reached.
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`.
```text
D1 query result exceeded the maximum response size limit of 50 MB
```
The combined D1 storage limit for a Workers Paid account increased from
250 GB to 1 TB.
### Alpha backup retirement and export behavior
As of July 1, 2025, Wrangler v3's `wrangler d1 backup` can no longer create
or access D1 alpha backups. Previously saved alpha backups can still be used to migrate
to a new generally available D1 database.
A running `wrangler d1 export` blocks other database requests.
Pass `--compatibility=sqlite3_cli_only` to include virtual tables such as
FTS5 and R*Tree. For the export API, set `dump_options.compatibility` to
`sqlite3_cli_only` in the POST body.
## Migrations and local development
Set `migrations_pattern` on the binding to discover nested migration files.
Its 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/**/*.sql` for any depth. The migrations table records paths
relative to `migrations_dir`. `wrangler d1 migrations create` writes at the
top level; for a nested-only pattern, use the ORM's generator, such as
`drizzle-kit generate`.
Applied migrations use `d1_migrations` by default; configure
`migrations_table` on the D1 binding to change the table name.
Wrangler v3 and later persist local D1 data across `wrangler dev` runs by
default; Wrangler v2 needs `--persist` to keep data.
For Pages, set `preview_database_id` to the binding name and keep
`database_id` set to the database UUID. For tests using `unstable_dev()`,
set `preview_database_id` to a user-defined value such as `local-test-db`
and apply migrations with `--local` before starting the test server.
## Binding and SQL essentials
D1 accepts only anonymous `?` and numbered `?NNN` placeholders.
Supply numbered-placeholder values to `bind()` in parameter-number order.
Bound booleans are stored as SQLite `INTEGER` and read as JavaScript `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.
Retrieving a large SQLite `int64` can lose precision because numeric results
use JavaScript numbers.
`run()` and `all()` are aliases returning a `D1Result` with `results` and `meta`.
`results` is `[]` for an empty row set and `null` when row results do not apply.
`batch()` returns one result per prepared statement in input order, each with
its own rows and metadata. Python Workers use `.to_py()` on the row array.
`raw({ columnNames: true })` returns column names as its first inner array.
`first(columnName)` returns `null` when there are no rows; D1 checks for the
requested column only when a row exists.
Supply newline-separated statements without parameter bindings to `exec()`.
It returns `{ count, duration }`, with duration in milliseconds. A failure
includes query and error messages and stops execution before remaining statements.
Run `PRAGMA optimize` after a schema change such as adding an index.
`PRAGMA optimize(-1)`, the SQLite dry-run form, is unavailable in D1.
D1 accepts `LIMIT` on `UPDATE` and `DELETE` to cap rows changed.
`ON DELETE CASCADE` actions still execute with `PRAGMA defer_foreign_keys = ON`.
## Read replication and sessions
Enabling replication provisions one replica per supported region, including
the primary's region. Replicas activate based on query traffic and have no
additional charge. Jurisdiction-restricted databases have replicas only
within their jurisdiction.
Use **Settings → Enable Read Replication** in the database dashboard, or
set `read_replication.mode` to `auto` or `disabled` with a database-endpoint
`PUT` and a `D1:Edit` token. A `GET` with `D1:Read` reports
`result.read_replication.mode`.
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.
Queries in either session are sequentially consistent.
`session.getBookmark()` returns the latest bookmark, or `null` before the
first query in a session started without a bookmark. Pass a saved bookmark
to `withSession()` to start at a database version at least as recent as the
one that bookmark identifies.
Session code works with replication disabled; replicas can take up to 24 hours
to stop serving requests after disablement.
Remote results include `meta.served_by_region` and `meta.served_by_primary`
regardless of session use or replication settings. Both are `undefined`
for local D1 queries in `wrangler dev`.
## Recovery, transfer, and placement
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.
The restore window is 7 days on Workers Free and 30 days on Workers Paid;
restore granularity is any minute within that window. History and restores
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. The undelete API accepts requests within seven days of deletion
and returns an error for older deletions.
For SQLite dumps, remove `BEGIN TRANSACTION`, `COMMIT`, and any
`CREATE TABLE _cf_KV` statement before importing. Split imports larger than
5 GiB across SQL files. Split oversized multi-row `INSERT` statements into
smaller statements. Create referenced tables before dependent rows; place
`PRAGMA defer_foreign_keys = true` before import writes to defer checks
until the transaction ends.
Use Workflows to export D1 through the REST API into R2 for retention beyond
the Time Travel window. Use export `--table` with `--no-data` for selected
schema or with `--no-schema` for selected data.
By default, D1 places the primary near the origin of the creation request.
A creation-time `--location` hint prefers a region; D1 chooses the nearest
available location by latency to the hint. A jurisdiction guarantees where
the database runs and stores data and takes precedence over a location hint.
An existing database cannot gain or change a jurisdiction. Supported
jurisdictions include `eu`, `fedramp`, and `us`; Workers can access a
jurisdiction-restricted database from anywhere.
## Diagnostics and retries
Log `error.message` for detailed binding errors; before Wrangler 3.1.1,
read `error?.cause?.message`. `D1_ERROR` is only a generic prefix.
`D1_TYPE_ERROR` can indicate bound `undefined`; use `null` for SQL NULL.
The HTTP query API returns `400 Bad Request` for invalid SQL and
`429 Too Many Requests` when the database is overloaded.
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 attempts including the initial execution.
If an automatic retry makes a database write, D1 rolls back that attempt.
Retry documented transient errors at application level only for idempotent
operations. The operations reference lists exact errors and resource responses.
`meta.timings.sql_duration_ms` measures database-instance SQL execution time
excluding network time. GraphQL Analytics exposes per-database read/write
rates, response sizes, and query latency percentiles.
D1 Insights recommendations include a `CREATE INDEX` statement, the queries
it is expected to speed up, and usage metrics. Enable or disable recommendations
through the dashboard, the `cf` CLI, or the API.
## AI Search data source (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 binding-and-SQL reference contains the instance-creation
request, including `source_params.d1.query` and the service-token setting.