---
title: Cloudflare D1
description: SQLite driver for Cloudflare D1 using Worker bindings
---

## Requirements

- Cloudflare Workers environment (no `nodejs_compat` flag needed)

## Configuration

```typescript
import { createClient } from "viborm/d1";

export default {
  async fetch(request: Request, env: Env) {
    const client = createClient({
      database: env.DB, // D1 binding from wrangler.toml
      schema,
    });

    const users = await client.user.findMany();
    return Response.json(users);
  },
};
```

## Options

| Option | Type | Description |
|--------|------|-------------|
| `database` | `D1Database \| D1DatabaseSession` | D1 database binding or session from Worker env |

`createClient` refuses any other key with a `ClientInitializationError` that
names it.

### Database sessions

Pass a session created for the current request as the database:

```typescript
import { createClient } from "viborm/d1";

const session = env.DB.withSession("first-primary");
const client = createClient({ database: session, schema });
const users = await client.user.findMany();
```

## Binary values

Blob fields bind `Uint8Array` values directly to D1, and D1's byte-array
results are normalized back to a plain `Uint8Array` — no Node `Buffer` or
`nodejs_compat` flag involved.

## GeoPoint storage tier

D1 uses the checked SQLite GeoPoint JSON carrier. Typed CRUD, equality,
inclusive ordinary/antimeridian bounds, nullability, native array batches,
relations, extensions, and cache are covered by the Workers substrate.
Polygon, distance, `_distance`, and spatial indexes refuse before a D1 call.
See [GeoPoint](/docs/schema/scalars/point).

### wrangler.toml

```toml
[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
```

## Transactions and batching

D1 does not support an interactive callback transaction. VibORM uses the
binding's native `batch()` primitive for work that can be planned up front.

### Atomic array transactions

The array API is one atomic D1 batch:

```typescript
const [user, post] = await client.$transaction([
  client.user.create({ data: { name: "Alice", email: "alice@example.com" } }),
  client.post.create({ data: { title: "Hello", authorId: "preset-id" } }),
]);
```

Every operation in this array must be plannable up front. That includes a
relation-bearing `createMany`, even one whose later row looks for a row an
earlier row creates (the call knows the rows it creates), and a nested create
whose parent key the database generates: the whole array commits together,
and if any statement fails nothing in the array is written.

An operation that must read what only the database can say after one of its
own writes (rows a cascade or a trigger may have changed) cannot be planned
into one batch. It is refused with a `TransactionError` (`V5001`) before the
batch is submitted, because `$transaction([...])` promises one atomic commit.

### Interactive transactions

Dynamic transactions (callback API) are unsupported and reject:

```typescript
// Throws TransactionError: D1 does not support callback transactions
await client.$transaction(async (tx) => {
  const user = await tx.user.create({ data: { name: "Alice" } });
  await tx.post.create({ data: { title: "Hello", authorId: user.id } });
});
```

### Relation-bearing bulk writes

A relation-bearing `createMany` or `updateMany`, at the root or nested, is
sent as **one D1 batch** whenever none of its rows has to hear the database
before the next can be written. The call knows the rows it creates: a later
row that looks for a row an earlier row creates finds it without a batch being
sent in between. Such a write succeeds or leaves nothing:

```ts
try {
  await client.post.createMany({
    data: [
      { id: "p1", author: { create: { id: "a1", name: "first" } } },
      { id: "p2", author: { create: { id: "a2", name: "occupied" } } },
    ],
  });
} catch {
  // The second author's name is taken: neither post and neither author exists.
}
```

A write that must read the database between two of its own writes takes one
batch after another (what goes into one batch is described under
[nested writes and failures per driver](/docs/drivers#nested-writes-and-failures-per-driver)):

- one submitted batch is atomic;
- successful results match transaction-capable drivers;
- if a later batch fails, earlier batches stay committed;
- the error reports what stands, in `meta.recordSeriesProgress`;
- VibORM never retries an already committed batch.

```ts
// error.toJSON().meta.recordSeriesProgress, where an earlier batch stands:
// {
//   atomicity: "segment",
//   phase: "member",
//   committedSegments: 1,
//   completedMembers: 1,
//   committedWriteMembers: 1
// }
```

`completedMembers` is the completed input prefix.
`committedWriteMembers` counts members whose user-table writes are durable.
`committedSegments` counts committed D1 batches.

When mutation-cache invalidation fails after a member has committed, the series
stops there and the client raises `CacheConfigurationError` (`V10004`) with
`meta.commitCertainty: "committed"`; the later members are not attempted.

A relation-bearing or nested `createMany({ skipDuplicates: true })` needs a
member rollback region that D1 does not provide. Preparation raises
`UnsupportedOperationError` before any parent or earlier member writes. Root
scalar `createMany` skipping remains supported through SQL conflict handling.

A database-generated integer key reaches the statements that need it through a
scratch table inside the same batch (see below), and a later segment binds the
concrete key. VibORM never derives a range of generated keys from
`meta.last_row_id` and never assumes adjacent values for a multi-row insert.

Scalar bulk operations and other statically planned nested writes continue to
use one atomic D1 batch. Inside that batch, a splittable `createMany` statement
is divided into the largest chunks that fit D1's conservative 100-bound-value
budget. The same applies to a many-to-many `connect`/`set` junction insert over
an already captured target-key list. The complete operation still succeeds or
rolls back as one D1 batch.

A raw statement (`$queryRawUnsafe`, `$executeRawUnsafe`, and the tagged forms)
is never split: past 100 bound values it is refused before D1 with
`UnsupportedOperationError` naming the count, inside an array `$transaction`
too, instead of D1's opaque error.

### The `__viborm_batch_refs` table

A batch that carries a value one statement produced into a later statement —
a generated parent key, typically — stores it in a scratch table. On other
SQLite drivers that table is `TEMP` and never enters the database file. D1
refuses temporary objects, so on D1 it is an ordinary table,
`__viborm_batch_refs`, created by the first batch that needs it and kept:

- it is empty between batches — each batch deletes the rows it stored, keyed by
  its own batch id, before it ends, and a failed batch rolls them back;
- VibORM's SQLite introspection leaves it out of the snapshot, so a `diff`
  over a database that holds it does not plan its drop;
- dropping it while no request is running is harmless: the next batch that
  needs it creates it again.

### Migrations

Migration V1 admits offline generation and read-only command paths on D1, and
refuses live `push`, `apply`, `down`, `reset`, and locked `verify`
before SQL. D1's native batch alone does not prove table recreation,
foreign-key handling, migration locking, and marker compare-and-swap together.
Apply live schema changes with `wrangler d1 migrations` instead.

Offline `generate` and `check` and estate-only inspection do not read the
database. `apply({ dryRun: true })` and `down({ dryRun: true })` read the live
marker without a lock and require a working D1 binding. `reset({ dryRun: true })`
previews the estate's root-to-target path without database reads, after target
and read-only capability admission. Read-only introspection over the binding
excludes D1-owned `_cf_` system tables before reading table metadata. User
tables remain visible. Local Workers evidence does not establish hosted
Cloudflare migration qualification. See
[migration atomicity](/docs/migration#atomicity).

## Capabilities

Interactive transactions reject. Static work uses one native atomic batch.
Root dynamic relation-bearing bulk uses ordered segment-atomic batches with
reported progress. See the [feature matrix](/docs/drivers#feature-matrix) for
the full comparison.

## Limitations

- Operations inside `$transaction([...])` cannot read sibling results.
- Only available in Cloudflare Workers
- SQLite dialect - no `LATERAL` joins, limited `FULL OUTER JOIN`
- JSON columns are parsed automatically
- Boolean values stored as integers (0/1)
