Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 52 additions & 49 deletions src/content/docs/d1/tutorials/d1-and-prisma-orm/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ languages:
- SQL
---

import { WranglerConfig, FileTree, PackageManagers } from "~/components";
import { WranglerConfig, FileTree, PackageManagers, GitHubCode } from "~/components";

## What is Prisma ORM?

Expand All @@ -21,14 +21,24 @@ To learn more about Prisma ORM, refer to the [Prisma documentation](https://www.

## Query D1 from a Cloudflare Worker using Prisma ORM

This example shows you how to set up and deploy a Cloudflare Worker that is accessing a D1 database from scratch.
This tutorial shows you how to set up and deploy a Cloudflare Worker that is accessing a D1 database from scratch.

### Prerequisites
## Quick start

If you want to skip the steps and get started quickly, select **Deploy to Cloudflare** below.

[![Deploy to Cloudflare](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/cloudflare/docs-examples/tree/d1-prisma/d1/query-d1-using-prisma)

This creates a repository in your GitHub account and deploys the application to Cloudflare Workers. Use this option if you are familiar with Cloudflare Workers, and wish to skip the step-by-step guidance.

You may wish to manually follow the steps if you are new to Cloudflare Workers.

## Prerequisites

- [`Node.js`](https://nodejs.org/en/) and [`npm`](https://docs.npmjs.com/getting-started) installed on your machine.
- A [Cloudflare account](https://dash.cloudflare.com).

### 1. Create a Cloudflare Worker
## 1. Create a Cloudflare Worker

Open your terminal, and run the following command to create a Cloudflare Worker using Cloudflare's [`hello-world`](https://github.com/cloudflare/workers-sdk/tree/4fdd8987772d914cf50725e9fa8cb91a82a6870d/packages/create-cloudflare/templates/hello-world) template:

Expand All @@ -41,7 +51,7 @@ In your terminal, you will be asked a series of questions related your project:
1. Answer `yes` to using TypeScript.
2. Answer `no` to deploying your Worker.

### 2. Initialize Prisma ORM
## 2. Initialize Prisma ORM

:::note

Expand Down Expand Up @@ -80,15 +90,15 @@ Since you will use the [driver adapter](https://www.prisma.io/docs/orm/overview/

Open your `schema.prisma` file and adjust the `generator` block to reflect as follows:

```diff
```prisma title="schema.prisma"
generator client {
provider = "prisma-client-js"
output = "../src/generated/prisma"
previewFeatures = ["driverAdapters"]
}
```

### 3. Create your D1 database
## 3. Create your D1 database

In this step, you will set up your D1 database. You can create a D1 database via the [Cloudflare dashboard](https://dash.cloudflare.com), or via `wrangler`. This tutorial will use the `wrangler` CLI.

Expand Down Expand Up @@ -141,7 +151,7 @@ Replace `<D1_DATABASE_ID>` with the database ID of your D1 instance. If you were

Next, you will create a database table in the database to send queries to D1 using Prisma ORM.

### 4. Create a table in the database
## 4. Create a table in the database

[Prisma Migrate](https://www.prisma.io/docs/orm/prisma-migrate/understanding-prisma-migrate/overview) does not support D1 yet, so you cannot follow the default migration workflows using `prisma migrate dev` or `prisma db push`.

Expand All @@ -151,7 +161,7 @@ Prisma Migrate for D1 is currently in Early Access. If you want to try it out, y

:::

D1 uses [migrations](/d1/reference/migrations) for managing schema changes, and the Prisma CLI can help generate the necessary SQL for those updates. In the steps below, you'll use both tools to create and apply a migration to your database.
D1 uses [migrations](/d1/reference/migrations) for managing schema changes, and the Prisma CLI can help generate the necessary SQL for those updates. In the steps below, you will use both tools to create and apply a migration to your database.

First, create a new migration using `wrangler`:

Expand All @@ -175,13 +185,16 @@ Next, you need to add the SQL statement that will create a `User` table to that

Open the `schema.prisma` file and add the following `User` model to your schema:

```diff
model User {
id Int @id @default(autoincrement())
email String @unique
name String?
}
```
<GitHubCode
repo="cloudflare/docs-examples"
file="d1/query-d1-using-prisma/prisma/schema.prisma"
commit="c49d24f86dc2eb06a07b1c0b3ede871a1d8e7e92"
lines="15-19"
lang="prisma"
code={{
title: "schema.prisma"
}}
/>

Now, run the following command in your terminal to generate the SQL statement that creates a `User` table equivalent to the `User` model above:

Expand All @@ -191,17 +204,16 @@ npx prisma migrate diff --from-empty --to-schema-datamodel ./prisma/schema.prism

This stores a SQL statement to create a new `User` table in your migration file from before, here is what it looks like:

```sql
-- CreateTable
CREATE TABLE "User" (
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"email" TEXT NOT NULL,
"name" TEXT
);

-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");
```
<GitHubCode
repo="cloudflare/docs-examples"
file="d1/query-d1-using-prisma/migrations/0001_create_user_table.sql"
commit="c49d24f86dc2eb06a07b1c0b3ede871a1d8e7e92"
lang="sql"
lines="1-9"
code={{
title: "0001_create_user_table.sql"
}}
/>

`UNIQUE INDEX` on `email` was created because the `User` model in your Prisma schema is using the [`@unique`](https://www.prisma.io/docs/orm/reference/prisma-schema-reference#unique) attribute on its `email` field.

Expand Down Expand Up @@ -253,7 +265,7 @@ npx wrangler d1 execute prisma-demo-db --command "INSERT INTO `"User`" (`"email

:::

### 5. Query your database from the Worker
## 5. Query your database from the Worker

To query your database from the Worker using Prisma ORM, you need to:

Expand All @@ -263,33 +275,24 @@ To query your database from the Worker using Prisma ORM, you need to:

Open `src/index.ts` and replace the entire content with the following:

```ts
import { PrismaClient } from './generated/prisma/';
import { PrismaD1 } from "@prisma/adapter-d1";

export interface Env {
DB: D1Database;
}

export default {
async fetch(request, env, ctx): Promise<Response> {
const adapter = new PrismaD1(env.DB);
const prisma = new PrismaClient({ adapter });

const users = await prisma.user.findMany();
const result = JSON.stringify(users);
return new Response(result);
},
} satisfies ExportedHandler<Env>;
```
<GitHubCode
repo="cloudflare/docs-examples"
file="d1/query-d1-using-prisma/src/index.ts"
commit="c49d24f86dc2eb06a07b1c0b3ede871a1d8e7e92"
lang="ts"
code={{
title: "index.ts"
}}
useTypeScriptExample={true}
/>

Before running the Worker, generate Prisma Client with the following command:

```sh
npx prisma generate
```

### 6. Run the Worker locally
## 6. Run the Worker locally

Now that you have the database query in place and Prisma Client generated, run the Worker locally:

Expand All @@ -303,7 +306,7 @@ Open your browser at [`http://localhost:8787`](http://localhost:8787/) to check
[{ "id": 1, "email": "[email protected]", "name": "Jane Doe (Local)" }]
```

### 7. Deploy the Worker
## 7. Deploy the Worker

To deploy the Worker, run the following command:

Expand Down
Loading