# Cloudflare D1

> How to use Reylo with Cloudflare D1 in a Worker. The Vite plugin, the schema the type check reads, queries, migrations through Wrangler, tests, and the SQLite functions D1 blocks.

Reylo on Cloudflare D1

D1 is SQLite, so everything on the [SQLite](https://reylo.dev/sqlite) page holds for it. A Durable Object's own database is on [Durable Objects](https://reylo.dev/durable-objects).

| | |
| --- | --- |
| Database | D1, through its binding |
| Bundler | Vite, with Cloudflare's Vite plugin |
| Tests | Vitest inside workerd, with Cloudflare's Vitest plugin |
| Postgres and MySQL in a Worker | Neon's serverless driver and PlanetScale's need nothing more. postgres.js, `pg`, `mysql2` and `mariadb` need Node's APIs: a compatibility date from 2026-08-04 on, or the `nodejs_compat` flag. Through Hyperdrive, which refuses prepared statements, Reylo runs [`mysql2`](https://reylo.dev/mysql#mysql2) through `query()` ([Cloudflare Hyperdrive](https://reylo.dev/hyperdrive)) |
| Example | [cloudflare-workers](https://github.com/reylosql/reylo/tree/main/examples/cloudflare-workers), a Worker with D1 and a Durable Object that runs locally with no Cloudflare account |

**View the schema behind the examples**

```sql
create table users (
  id integer primary key,
  name text not null,
  email text,
  created_at text not null default current_timestamp
) strict;
```

## Setup

Add Reylo's Vite plugin beside Cloudflare's:

`vite.config.ts`:

```ts
import { cloudflare } from "@cloudflare/vite-plugin";
import { defineConfig } from "vite";
import reylo from "reylo/vite";

export default defineConfig({
  plugins: [reylo(), cloudflare()],
});
```

- Import each `.sql` file by a relative path. A path through an alias, such as a tsconfig `paths` entry, reaches the Cloudflare plugin's text rule before Reylo.
- A Worker that only uses D1 needs no `nodejs_compat` flag.

## Local database

The type check reads your schema from a local SQLite file. Point [`direct_url`](https://reylo.dev/configuration#direct_url) at it:

`.reylo.yaml`:

```yaml
direct_url: file:./dev.sqlite
```

Your [migrations](https://reylo.dev/d1#migrations) create it:

```sh
reylo migrate dev
```

- Set it in `.reylo.yaml`, not in `.env`: Wrangler loads `.env` into the Worker as secrets.
- Keep it apart from the local D1 database that Wrangler keeps, which Wrangler migrates itself.
- In CI, run `reylo migrate deploy` before the build. The type check needs no access to the remote database.
- With migrations written for Wrangler alone, point `direct_url` at Wrangler's local D1 file instead: `.wrangler/state/v3/d1/miniflare-D1DatabaseObject/<name>.sqlite`, named after the binding's `database_id`.

## Queries

Pass the binding, or a session from `.withSession()`:

`worker.ts`:

```ts
import type { D1Database } from "@cloudflare/workers-types";
import getUser from "./get_user.sql";

export default {
  async fetch(request: Request, env: { DB: D1Database }) {
    const user = await getUser.run(env.DB, { id: 1 });
    const sameUser = await getUser.run(env.DB.withSession(), { id: 1 });
    return Response.json(user);
  },
};
```

`get_user.sql`:

```sql
select id, name, email from users where id = :id
```

- D1 has no transaction a query can join. Its `batch()` takes D1's own prepared statements.
- D1 rounds an integer past 2^53, so Reylo throws an error rather than return it, even for a `BIGINT` column.

## Migrations

Write your migrations with [`reylo migrate`](https://reylo.dev/migrate/docs), and let Wrangler run them on D1:

`wrangler.jsonc`:

```jsonc
{
  // ...
  "d1_databases": [
    { "binding": "DB", "database_name": "app", "migrations_dir": "reylo/migrations" }
  ]
}
```

```sh
wrangler d1 migrations apply DB --remote
```

On a D1 database that already has tables, the `init.sql` that `reylo migrate init` writes describes what D1 has. Record it as applied, so that Wrangler doesn't run it:

```sh
wrangler d1 execute DB --remote --command "insert into d1_migrations (name) values ('init.sql')"
```

On a new D1 database for that project, Wrangler would run `init.sql` last, since it applies files in name order. Run it first and record it, then apply the rest:

```sh
# makes Wrangler's d1_migrations table
wrangler d1 migrations list DB --remote
wrangler d1 execute DB --remote --file reylo/migrations/init.sql
wrangler d1 execute DB --remote --command "insert into d1_migrations (name) values ('init.sql')"
wrangler d1 migrations apply DB --remote
```

## Blocked functions

D1 blocks some of SQLite's functions, such as `json_pretty` and `power`. The type check also runs each query on Cloudflare's SQLite, as Wrangler runs it locally, so a blocked function is a type error. It does so when your `package.json` has `wrangler` and its config has a D1 database:

`wrangler.jsonc`:

```jsonc
{
  // ...
  "d1_databases": [{ "binding": "DB", "database_name": "app" }]
}
```

## Tests

Run the tests inside workerd with Cloudflare's Vitest plugin, and Reylo's beside it:

`vitest.config.ts`:

```ts
import { cloudflareTest } from "@cloudflare/vitest-plugin";
import { defineConfig } from "vitest/config";
import reylo from "reylo/vite";

export default defineConfig({
  plugins: [
    reylo(),
    cloudflareTest({ wrangler: { configPath: "./wrangler.jsonc" } }),
  ],
});
```

Wrangler makes every imported `.sql` file a text module, and the Vitest plugin applies that rule before Vite runs any plugin. List Wrangler's other text types so that `.sql` is left to Reylo:

`wrangler.jsonc`:

```jsonc
{
  // ...
  // wrangler's default text types, without .sql
  "rules": [{ "type": "Text", "globs": ["**/*.txt", "**/*.html"] }]
}
```

## Without Vite

Wrangler's own bundler takes no plugins, but it runs a custom build first, on `wrangler dev` and `wrangler deploy`. Build with esbuild and Reylo's esbuild plugin:

`wrangler.jsonc`:

```jsonc
{
  // ...
  "main": "dist/worker.js",
  "build": { "command": "node build.ts", "watch_dir": ["src", "queries"] }
}
```

`build.ts`:

```ts
import * as esbuild from "esbuild";
import reylo from "reylo/esbuild";

await esbuild.build({
  entryPoints: ["src/worker.ts"],
  bundle: true,
  format: "esm",
  platform: "neutral",
  plugins: [reylo()],
  outfile: "dist/worker.js",
});
```
