The best way to control Claude Code, Codex and more from any computer or phone

main
mdx 190 lines 6.22 KB
Raw
1 ---
2 title: D1
3 description: Cloudflare D1 is serverless SQLite — create a database, apply migrations on deploy, and query it from a Worker through a typed binding.
4 ---
5
6 D1 is Cloudflare's serverless SQLite database. There's nothing to
7 provision or scale — you get a SQL database addressed by name, with
8 reads served close to your users when read replication is enabled.
9
10 Reach for D1 when your app needs relational data without operating a
11 database: user tables, content, app state queried with plain SQL. If
12 you need Postgres or MySQL (or already have one), front it with
13 [Hyperdrive](/cloudflare/data/hyperdrive) instead.
14
15 ## Create a database
16
17 A database is one resource declaration:
18
19 ```typescript
20 // src/database.ts
21 import * as Cloudflare from "@alchemy.run/cloudflare";
22
23 export const Database = Cloudflare.D1.Database("Database");
24 ```
25
26 Yield it inside your Stack like any other resource:
27
28 ```typescript
29 // alchemy.run.ts
30 import * as Alchemy from "alchemy";
31 import * as Cloudflare from "@alchemy.run/cloudflare";
32 import * as Effect from "effect/Effect";
33 import { Database } from "./src/database.ts";
34
35 export default Alchemy.Stack(
36 "MyApp",
37 {
38 providers: Cloudflare.providers(),
39 state: Cloudflare.state(),
40 },
41 Effect.gen(function* () {
42 const db = yield* Database;
43
44 return { databaseName: db.databaseName };
45 }),
46 );
47 ```
48
49 ## Migrations
50
51 Point `migrations` at a folder of `.sql` files. Files are sorted
52 by numeric prefix (`0001_`, `0002_`, …) and applied in order as part
53 of every deploy; already-applied migrations are skipped:
54
55 ```typescript
56 const db = yield* Cloudflare.D1.Database("my-db", {
57 migrations: "./migrations",
58 });
59 ```
60
61 Bookkeeping lives in Alchemy's `__alchemy_migrations` table. A
62 database previously migrated with `wrangler d1 migrations apply` or
63 `drizzle-kit migrate` is
64 [adopted automatically](/sql/effect-sql/migrations#adopting-an-existing-database):
65 the old tool's applied history is copied in once and its table is
66 frozen — never written, never dropped. D1 has no transactions over
67 HTTP, so each migration and its bookkeeping row are sent as one
68 batched query, matching wrangler's own behavior.
69
70 The migration files themselves don't have to be hand-written —
71 [Drizzle.Schema](/sql/drizzle/migrations) can generate them from a
72 Drizzle schema on deploy. [Drizzle on D1](/cloudflare/data/d1-drizzle)
73 walks through the whole flow: schema → generated migrations → typed
74 queries from the Worker.
75
76 ## Query from a Worker
77
78 Bind the database into a Worker with `Cloudflare.D1.QueryDatabase`
79 and provide the `QueryDatabaseBinding` layer. The client exposes
80 `prepare`, `exec`, `batch`, and `raw`; prepared statements execute
81 with `all`, `first`, or `run`:
82
83 ```typescript
84 // src/worker.ts
85 import * as Cloudflare from "@alchemy.run/cloudflare";
86 import * as Effect from "effect/Effect";
87 import * as HttpServerResponse from "effect/http/HttpServerResponse";
88 import { Database } from "./database.ts";
89
90 export default Cloudflare.Worker(
91 "Worker",
92 { main: import.meta.url },
93 Effect.gen(function* () {
94 // Construction: register the binding, get a typed client
95 const db = yield* Cloudflare.D1.QueryDatabase(Database);
96
97 return {
98 fetch: Effect.gen(function* () {
99 // runtime: run queries
100 const results = yield* db
101 .prepare("SELECT * FROM users WHERE id = ?")
102 .bind(1)
103 .all();
104 return yield* HttpServerResponse.json(results);
105 }),
106 };
107 }).pipe(Effect.provide(Cloudflare.D1.QueryDatabaseBinding)),
108 );
109 ```
110
111 `prepare` and `bind` are synchronous plan builders — only the
112 executors (`all`, `first`, `run`, `raw`) round-trip to the database,
113 and those return Effects. For libraries that want the native
114 `D1Database` object (e.g. Better Auth), use the client's `raw`
115 escape hatch.
116
117 ## SQL with `@effect/sql-d1`
118
119 Prefer tagged-template SQL over hand-written prepared statements?
120 `SQL.D1` (from `@alchemy.run/cloudflare/D1/SQL` — each low-level effect-sql client
121 lives on its own subpath) wraps the same binding in an
122 `@effect/sql-d1` `D1Client` —
123 interpolated values are parameterized, every query is an Effect, and
124 failures surface as typed `SqlError`s:
125
126 ```typescript
127 import * as SQL from "@alchemy.run/cloudflare/D1/SQL";
128
129 Effect.gen(function* () {
130 const d1 = yield* Cloudflare.D1.QueryDatabase(Database);
131 const sql = yield* SQL.D1(d1);
132
133 return {
134 fetch: Effect.gen(function* () {
135 const id = 1;
136 const users = yield* sql`SELECT * FROM users WHERE id = ${id}`;
137 return yield* HttpServerResponse.json({ users });
138 }),
139 };
140 }).pipe(Effect.provide(Cloudflare.D1.QueryDatabaseBinding));
141 ```
142
143 The client is built lazily on the first query and memoized per
144 execution — a `fetch`/`queue`/`scheduled` event, a Durable Object
145 call, or a Workflow run — then torn down when the event settles.
146
147 `D1Client` implements Effect's generic `SqlClient` interface, so
148 services written against `SqlClient.SqlClient` run on D1 unchanged.
149 Provide both tags with the layer form:
150
151 ```typescript
152 import * as SqlClient from "effect/sql/SqlClient";
153
154 const makeApp = Effect.gen(function* () {
155 const sql = yield* SqlClient.SqlClient;
156 // ... services that only know about SqlClient
157 });
158
159 const app = yield* makeApp.pipe(
160 Effect.provide(SQL.D1Layer(d1)),
161 );
162 ```
163
164 The complete runnable project is
165 [`cloudflare-effect-sql-d1`](https://github.com/alchemy-run/alchemy/tree/main/examples/cloudflare-effect-sql-d1).
166 The full client API, the Layer pattern, and the lifecycle contract
167 live in the SQL hub — [Effect SQL: D1](/sql/effect-sql/d1) and
168 [Connection lifecycle](/sql/effect-sql/lifecycle). For typed schemas
169 and an ORM on top of the same binding, see
170 [Drizzle on D1](/cloudflare/data/d1-drizzle).
171
172 ## Where next
173
174 Guides:
175
176 - [Drizzle on D1](/cloudflare/data/d1-drizzle) — typed schemas,
177 generated migrations, and the `effect-d1` driver on this database.
178 - [`cloudflare-effect-sql-d1`](https://github.com/alchemy-run/alchemy/tree/main/examples/cloudflare-effect-sql-d1)
179 — the runnable `@effect/sql-d1` example.
180
181 Related:
182
183 - [Workers](/cloudflare/compute/workers) — where your queries run.
184 - [Hyperdrive](/cloudflare/data/hyperdrive) — for external Postgres/MySQL
185 instead of SQLite.
186
187 Reference:
188
189 - [Database API reference](/providers/cloudflare/d1/database)
190 - [QueryDatabase API reference](/providers/cloudflare/d1/querydatabase)