Skip to content
TypeScript
5.1 KB
Raw Blame
---
title: D1
description: SQLite schemas and Effect-native Drizzle queries over a Cloudflare D1 binding.
---

import PackageManagers from "../../../../components/PackageManagers.astro";

export const deps = `@alchemy.run/drizzle [email protected] @effect/sql-d1`;
export const devDeps = `[email protected]`;

`Drizzle.D1` provides typed, Effect-native queries over a Cloudflare D1 binding; unlike Postgres and MySQL, this driver is Cloudflare-specific. See [SQL databases](/sql/databases) to compare engines and [Cloudflare setup](/cloudflare/setup) for deployment choices.

Install the toolchain — all optional peers of alchemy:

<PackageManagers add={deps} dev={devDeps} />

## Define the schema

Drizzle schemas are plain TypeScript modules using the
`sqlite-core` column builders:

```typescript
// src/schema.ts
import { defineRelations } from "drizzle-orm";
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";

export const Users = sqliteTable("users", {
  id: integer("id").primaryKey({ autoIncrement: true }),
  email: text("email").notNull().unique(),
  name: text("name").notNull(),
});

export const Posts = sqliteTable("posts", {
  id: integer("id").primaryKey({ autoIncrement: true }),
  userId: integer("user_id")
    .notNull()
    .references(() => Users.id, { onDelete: "cascade" }),
  title: text("title").notNull(),
});

export const relations = defineRelations({ Users, Posts }, (t) => ({
  Users: { posts: t.many.Posts() },
  Posts: {
    user: t.one.Users({ from: t.Posts.userId, to: t.Users.id }),
  },
}));
```

## Generate and review migrations

```typescript
// drizzle.config.ts
import { defineConfig } from "drizzle-kit";

export default defineConfig({
  schema: "./src/schema.ts",
  out: "./migrations",
  dialect: "sqlite",
});
```

```sh
bunx drizzle-kit generate
git add src/schema.ts drizzle.config.ts migrations
git diff --cached
git commit -m "Add database migration"
```

Generate with each schema change and review the schema, SQL, and snapshots together before committing. [Migrations](/sql/drizzle/migrations) covers application ownership; the optional [`Drizzle.Schema` resource](/providers/drizzle/schema) is not required.

## Declare the database

```typescript
// src/db.ts
import * as Cloudflare from "@alchemy.run/cloudflare";

export const Database = Cloudflare.D1.Database("app-db", {
  migrations: "./migrations",
});
```

With `Cloudflare.providers()` registered, the resource applies committed files during deploy without generating SQL. See the [Cloudflare D1 walkthrough](/cloudflare/data/d1-drizzle) for the full deployment; keep an existing migration runner unless you deliberately choose Alchemy-managed application.

## Connect in a Worker

Bind the database with `Cloudflare.D1.QueryDatabase` and hand the
client to `Drizzle.D1`:

```typescript
// src/api.ts
import * as Cloudflare from "@alchemy.run/cloudflare";
import * as Drizzle from "@alchemy.run/drizzle";
import * as Effect from "effect/Effect";
import * as HttpServerResponse from "effect/http/HttpServerResponse";
import { Database } from "./db.ts";
import { relations, Users } from "./schema.ts";

export default class Api extends Cloudflare.Worker<Api>()(
  "Api",
  { main: import.meta.url },
  Effect.gen(function* () {
    const database = yield* Database;
    const d1 = yield* Cloudflare.D1.QueryDatabase(database);
    const db = yield* Drizzle.D1(d1, { relations });

    return {
      fetch: Effect.gen(function* () {
        const users = yield* db.select().from(Users);
        return yield* HttpServerResponse.json({ users });
      }),
    };
  }).pipe(Effect.provide(Cloudflare.D1.QueryDatabaseBinding)),
) {}
```

Client construction does not query D1; the first query builds the client and reuses it within the event's [scope](/sql/effect-sql/lifecycle). Resource provisioning and migration application still run during deployment.

## Queries are Effects

Every builder yields directly, with `SqlError` in the typed error
channel:

```typescript
import { eq } from "drizzle-orm";

const [created] = yield* db
  .insert(Users)
  .values({ name, email })
  .returning();

const [removed] = yield* db
  .delete(Users)
  .where(eq(Users.id, id))
  .returning();
```

Because `relations` was passed to `Drizzle.D1`, the typed
`db.query.*` API is available:

```typescript
const user = yield* db.query.Users.findFirst({
  where: { id },
  with: { posts: true },
});
```

D1 has no session transactions — for atomic multi-statement writes
use the binding's `batch` (see
[Batches instead of transactions](/sql/effect-sql/d1#batches-instead-of-transactions)).

## Local dev

`alchemy dev` runs the same Worker against a local D1 database via
miniflare — `Drizzle.D1` works unchanged because it resolves
whatever `D1Database` binding the runtime provides.

## Where next

The [Cloudflare D1 walkthrough](/cloudflare/data/d1-drizzle) owns deployment, while [Effect SQL: D1](/sql/effect-sql/d1) covers tagged-template queries over the same binding. The [D1 example](https://github.com/alchemy-run/alchemy/tree/main/examples/cloudflare-d1-drizzle) demonstrates schema and query code but uses the optional schema resource rather than this guide's generation workflow.